D. String Deletion(思维+双指针模拟)

52 篇文章 1 订阅

https://codeforces.com/contest/1430/problem/D


观察到如果长度为1的相同块,咋样都会一次性消除。

只有长度>=2的,如果选他的话可以减少一次其他的多余消耗。而且如果有多个>=2的,那么模拟发现选最左边的是最优的。

先缩点。

然后模拟不断从左边的长度>=2的块去取。每次在循环中找到长度>=2的,长度减少到1就继续往右找。没了就只能累加i指针。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+100;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
char str[maxn];
LL a[maxn],tot=0;
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL t;cin>>t;
  while(t--){
    LL n;cin>>n;
    for(LL i=0;i<n+10;i++) a[i]=0,tot=0;
    cin>>(str+1);
    for(LL i=1;i<=n;i++){
        if(str[i]!=str[i-1]) a[++tot]=1;
        else a[tot]++;
    }
    LL now=1;LL sum=0;
    for(LL i=1;i<=tot;i++){
        while(now<=tot&&a[now]==1) now++;
        sum++;
        if(now<=tot){
            a[now]--;
        }
        else{
            i++;
        }
        if(i==now) now++;
    }
     cout<<sum<<"\n";
  }
return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值