题目大意
给你一个只有 0 0 0 和 1 1 1 的字符串,不断地进行翻折(前提是翻折后翻折所对应的格子里的字符相同),使得最后字符串的长度最小。
分析
很明显地发现,翻折时一定在某两个相邻且字符相等的格子之间为断点进行翻折。所以只要将它翻折直到最后剩下的字符串并无相邻的格子字符相同,即它为交替的形式,此时的答案即为最优解。时间复杂度为 O ( T × n ) O(T \times n) O(T×n)。
代码如下
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+100;
signed main()
{int T,c[N];scanf("%d",&T);while(T--){int n;scanf("%d",&n);char ch=getchar();while(ch!='1'&&ch!='0') ch=getchar();int j=0;while(ch=='1'||ch=='0'){c[++j]=ch-'0';ch=getchar();}int lft=0,rt=0,sum=0,ff=1;for(int i=2;i<=n;i++){if(c[i]==c[i-1]) ff=-ff;else sum+=ff;lft=(lft>sum?sum:lft);rt=(rt>sum?rt:sum);}printf("%d\n",rt-lft+1);}return 0;
}