CF EDU 107 D - Min Cost String

D - Min Cost String

若尽量让满足 \(s[i]==s[j],\;s[i+1]==s[j+1],\;i<j\)\((i,j)\) 对越少,若把 \(a-z\) 视为 \(0-25\)

可构造一种策略:记录一个 \(cnt[i]\) 表示数字 \(i\) 已经出现了几次,出现第 \(1\) 次时,\(i\) 后面可以是 \(i\)

当出现第 \(2\) 次时,为避免增加答案,\(i\) 后面为 \(i+1\)... 所以每次令下一个数为 \((last+cnt[last]) \mod k\) 即可

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>

using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
int n, k;
int a[N], cnt[30];
char s[N];
int main()
{
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n >> k;
	a[0] = 0;
	for (int i = 1; i < n; i++)
	{
		int last = a[i-1];
		a[i] = (last + cnt[last]) % k;
		cnt[last]++;	
	}
	for (int i = 0; i < n; i++)
		s[i] = 'a' + a[i];
	cout << s << endl;
	return 0;
}
posted @ 2022-05-17 22:58  hzy0227  阅读(22)  评论(0编辑  收藏  举报