codeforces Round 96 Div2 D

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:

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);
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.

Example
inputCopy
5
6
111010
1
0
1
1
2
11
6
101010
outputCopy
3
1
1
1
3
Note
In the first test case, you can, for example, select i=2 and get string 010 after the first operation. After that, you can select i=3 and get string 1. Finally, you can only select i=1 and get empty string.

#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<cmath>
using namespace std;
int t,n,ans,cnt;
int a[200010];
string s;
int main()
{
	cin>>t;
	while(t--)
	{
		cin>>n>>s;
		ans=0;
		cnt=0;
		memset(a,0,sizeof(a));
		a[0]=1;
		for(int i=1;i<s.size();i++)
			if(s[i]==s[i-1])
				a[cnt]++;
			else
				a[++cnt]++;
		for(int i=0,j=0;i<=cnt;i++)
		{
			if(a[i]>1)
			{
				ans++;
				continue;
			} 
			j=max(j,i+1);
			int k=0;
			for(;j<=cnt;j++)
			{
				if(a[j]>=2)
				{
					a[j]--;
					k=1;
					break;
				}
			}
			if(!k)
				i++;
			ans++;
		}
		cout<<ans<<endl;
	}	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值