Codeforces C. K-beautiful Strings (字符串反向贪心枚举) (Round #705 Div.2)

传送门

题意: 给你一个长度为n的字符串s,要求你找到比s大的最小长度为n的字符串c,且必须满足c中每个字符出现的次数都能整除k,若找不到合法的字符串输出"-1"。

思路:参考官方题解代码和大佬思路解析,细节见代码注释。

代码实现:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {
   
   {1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9+7;
const int  N = 2e5 + 5;

inline void read(int &x){
    char t=getchar();
    while(!isdigit(t)) t=getchar();
    for(x=t^48,t=getchar();isdigit(t);t=getchar()) x=x*10+(t^48);
}

char s[N];
int t, n, k, num[30];

inline int f(char ch){
	return ch-'a';
}
inline int get(int x){
    return (k-x%k)%k;
}

signed main()
{

	cin >> t;
	while(t --){
		cin >> n >> k >> s+1;
	    if(n%k){
	    	cout << -1 << endl;
	    	continue;
    	}
    	me(num);
	    int ret = 0;
	    for(int i = 1; i <= n; i ++) //统计每个字母的数量
	    	num[f(s[i])] ++;

    	for(int i = 0; i < 26; i ++)
    		ret += get(num[i]);  //统计总共还需要多少个字符来凑成合法的

    	if(!ret){
	    	cout << s+1 << endl; //字符串原本就是合法的
	    	continue;
	    }
	    int flag = 0;
	    for(int i = n; i >= 1; i --){
	    	num[f(s[i])] --;//换掉当前位置字符
	    	if(num[f(s[i])]%k==0) ret -= k-1; //表示该字母剩下的数量合法,那么需要凑的数量直接减少k-1个
		    else ret ++;  //否则还需要凑当前位置的字符
		    int g = ret;
		    for(int j = f(s[i])+1; j < 26; j ++){ //枚当前位置换成哪个字符合适
		    	ret -= get(num[j])-get(++num[j]); //更新当前需要的字符数——减去新增字符原先的需要数,再加上新增的需要数
		    	if(n-i>=ret&&(n-i-ret)%k==0){  //如果需要凑的字符数在剩下n-i个以内,且n-i个中除了需要凑的数外剩下的是k的倍数
		    		for(int h = 1; h < i; h ++)
				    	cout << s[h];  //输出前i个原始字符
				    cout << char(j+'a');
				    for(int h = 1; h <= n-i-ret; h ++) //由于第i个位置已经变成较大的字符,剩下的直接用最小的字符"a"填充
				        cout << "a";
                    for(int h = 0; h < 26; h ++)
                        for(int o = 1; o <= get(num[h]); o ++)//按照字典序从小到大填充相应的字符
						    cout << char(h+'a');
                    cout <<endl;
				    flag = 1;
				    break;
			    }
			    ret = g; //还原ret
			    num[j] --; //还原相应字符的数量
			    if(flag) break;
	    	}
	    }
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Satur9/article/details/114486149
今日推荐