Loading

Educational Codeforces Round 107 (Rated for Div. 2) D. Min Cost String(Map/贪心/瞎搞)

Let's define the cost of a string 𝑠s as the number of index pairs i and j (1≤i<j<|s|) such that si=sj and si+1=sj+1.

You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost — find any of them.

Input

The only line contains two integers 𝑛n and 𝑘k (1≤n≤2⋅10^5;1≤k≤26).

Output

Print the string 𝑠s such that it consists of 𝑛n characters, each its character is one of the 𝑘k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings — print any of them.

Examples

input

Copy

9 4

output

Copy

aabacadbb

input

Copy

5 1

output

Copy

aaaaa

input

Copy

10 26

output

Copy

codeforces

易知字符集为前k个字母的情况下长度为2的串一共有\(k^2\)个,我们最终的目标一定是想让整个字符串中所有\(s_is_{i + 1}\)这两位子串尽可能平均地分布在\(k^2\)个串中。因此可以用map记录一下这\(k^2\)个串每个串目前出现的次数,遍历到i时以通过上一个字母\(s_{i - 1}\)加上当前遍历的前k个字母中的某一个组成的串在map中的值要尽可能小(贪心)。

注意第二重循环遍历k个字母的时候一定要尽量避开字符串的第一个字符,比如答案字符串第一个字符我选择填a,那么第二重循环遍历的时候要么从k - 1遍历到0,要么从1遍历到k(对k取模)以保证最后才考虑a这个字符。

#include <bits/stdc++.h>
using namespace std;
map<string, int> mp;
int main() {
	int n, k;
	cin >> n >> k;
	if(k == 1) {
		for(int i = 1; i <= n; i++) cout << 'a';
		return 0;
	}
	string s = "";
	char c = 'a';
	s = s + c;
	for(int i = 1; i < n; i++) {
		int mmin = 0x3f3f3f3f;
		string pos = "";
		for(int j = k - 1; j >= 0; j--) {//必须倒序循环 否则wa 是因为第一个字符是a 导致得倒着贪心?
			string tmp = "";
			tmp += s[i - 1];
			tmp += (char)('a' + j);
			if(mp.find(tmp) == mp.end()) {
				pos = tmp;
				mp[tmp] = 0;
				mmin = 0;
				pos = tmp;
				break;
			} else {
				int x = mp[tmp];
				if(x < mmin) {
					pos = tmp;
					mmin = x;
				}
			}
		}
		mp[pos]++;
		s += pos[1];

	}
	cout << s;
	return 0;
}
posted @ 2021-04-14 09:18  脂环  阅读(94)  评论(0编辑  收藏  举报