C. K-beautiful Strings(思维+从后往前贪心+模拟)

104 篇文章 0 订阅

https://codeforces.com/contest/1493/problem/C


思路:

参考issue翻译的官方题解

所以对于判断可行的部分,直接给每一个字母开一个前缀和

#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=1e5+10;
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;}
LL sum[maxn][30];
char str[maxn];
LL tran(char s){
    return (s-'a'+1);
}
LL get(LL pos,LL num,LL mod){
      return (mod-sum[pos][num]%mod)%mod;
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL T;cin>>T;
  while(T--){
      LL n,k;cin>>n>>k;
      for(LL i=0;i<n+5;i++){
        for(LL j=1;j<=26;j++) sum[i][j]=0;
      }
      cin>>(str+1);
      for(LL i=1;i<=n;i++){
        for(LL j=1;j<=26;j++){
            sum[i][j]=sum[i-1][j];
        }
        sum[i][tran(str[i])]++;
      }
      if(n%k!=0){
        cout<<"-1"<<"\n";
        continue;
      }
      LL g=0;
      for(LL j=1;j<=26;j++){
         g+=get(n,j,k);
      }
      if(g==0){
        for(LL j=1;j<=n;j++) cout<<str[j];
        cout<<"\n";
        continue;
      }
      bool flag=1;
      for(LL i=n;1==flag&&i>=1;i--){///枚举第i位是否可以>
          for(char o=str[i]+1;o<='z';o++){
              LL pre=tran(str[i]);
              LL j=tran(o);
              sum[i][pre]--;
              sum[i][j]++;
              LL ans=0;
              for(LL p=1;p<=26;p++){
                ans+=get(i,p,k);
              }
              if(ans<=n-i+1){
                for(LL pos=1;pos<=i-1;pos++) cout<<str[pos];
                cout<<o;
                LL cnt=(n-i-ans);
                for(LL pos=1;pos<=cnt;pos++) cout<<"a";
                for(char ace='a';ace<='z';ace++){
                    LL num=get(i,tran(ace),k);
                    while(num>0) cout<<ace,num--;
                }
                cout<<"\n";
                flag=0;
                break;
              }
              sum[i][j]--;
              sum[i][pre]++;
          }
      }
      if(1==flag) cout<<"-1"<<"\n";
  }
return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值