MT27. 交错序列
描述
我们定义一个由数字 0 和 1 组成的序列是交错序列,当且仅当在这个序列中 0 和 1 是轮流 出现的,比如,0,010,10101 都是交错序列。输入描述
输出描述
输出能够得到的最长交错序列的长度。示例1
输入:
3 0 1 0
输出:
3
示例2
输入:
8 1 1 0 0 1 1 0 0
输出:
4
C 解法, 执行用时: 2ms, 内存消耗: 620KB, 提交时间: 2020-08-11
# include <stdio.h> int main() { int n; char buf[200000]={0}; char copy[200000]; scanf("%d", &n); getchar(); gets(buf); int count = 1; int j=0; for( int i=0; i<2*n-1; i++) { if(buf[i] != ' ') { copy[j] = buf[i]; j++; } } copy[j]='\0'; for( int i=0; i<j-1; i++) { if(copy[i] != copy[i+1]) { count += 1; } } printf("%d\n", count); return 0; }
C++ 解法, 执行用时: 6ms, 内存消耗: 488KB, 提交时间: 2020-08-03
#include<iostream> #include<stdio.h> using namespace std; int main() { int n; char op; char temp; scanf(" %d",&n); int length = 0; scanf(" %c",&temp); ++length; for(int i = 0; i < n - 1; i ++) { scanf(" %c",&op); if(temp ^ op) // 不相等 { if((length & 1)) { ++length; } } else { if(!(length & 1)) { ++length; } } } printf("%d",length); return 0; }