D. String Deletion
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You have a string s consisting of n characters. Each character is either 0 or 1.
You can perform operations on the string. Each operation consists of two steps:
1.select an integer i from 1 to the length of the string s, then delete the character si (the string length gets reduced by 1, the indices of characters to the right of the deleted one also get reduced by 1);
2.if the string s is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix).
Note that both steps are mandatory in each operation, and their order cannot be changed.
For example, if you have a string s= 111010, the first operation can be one of the following:
select i=1: we’ll get 111010 → 11010 → 010;
select i=2: we’ll get 111010 → 11010 → 010;
select i=3: we’ll get 111010 → 11010 → 010;
select i=4: we’ll get 111010 → 11110 → 0;
select i=5: we’ll get 111010 → 11100 → 00;
select i=6: we’ll get 111010 → 11101 → 01.
You finish performing operations when the string s becomes empty. What is the maximum number of operations you can perform?
Input
The first line contains a single integer t (1≤t≤1000) — the number of test cases.
The first line of each test case contains a single integer n (1≤n≤2⋅105) — the length of the string s.
The second line contains string s of n characters. Each character is either 0 or 1.
It’s guaranteed that the total sum of n over test cases doesn’t exceed 2⋅105.
Output
For each test case, print a single integer — the maximum number of operations you can perform.
方法:双指针+贪心
代码
#include<cstdio>
#include<iostream>
#include<cmath>
#include<set>
#include<cstring>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
typedef long long LL;
int a[200000];
int main()
{
int t;
scanf("%d",&t);
while(t--){
int strlen,n=1,m=0;
string s;
scanf("%d",&strlen);
cin>>s;
for(int i=0;i<strlen;i++){
if(i&&s[i]==s[i-1]) n++;
if(i&&s[i]!=s[i-1]){
a[m++]=n;
n=1;
}
}
a[m++]=n;
int p1=0,p2=0,ans=0;
while(1){
while(a[p2]==1&&p2<m) p2++;
if(p2>=m) break;
a[p2]--;p1++;ans++;
if(p2<p1) p2=p1;
}
if((p2-p1)%2) ans+=(p2-p1)/2+1;
else ans+=(p2-p1)/2;
printf("%d\n",ans);
}
return 0;
}
为使字符串在变为空串的过程中使用尽可能多的次数,我们应尽量避免长连通串被一次性消掉的情况,用p1模拟步骤2的操作,p2模拟步骤1的操作,用p2寻找靠近字符串前端的长连通串,并通过削减长连通串来增加字符串的可操作数。