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的串一共有k2个,我们最终的目标一定是想让整个字符串中所有sisi+1这两位子串尽可能平均地分布在k2个串中。因此可以用map记录一下这k2个串每个串目前出现的次数,遍历到i时以通过上一个字母si1加上当前遍历的前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 @   脂环  阅读(98)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2020-04-14 Codeforces Round #634 E2. Three Blocks Palindrome (hard version)(双指针/前缀和/二分/好题)
2020-04-14 Codeforces Round #634 D. Anti-Sudoku(构造/水)
2020-04-14 Codeforces Round #634 C. Two Teams Composing(排序)
2020-04-14 Codeforces Round #634 B. Construct the String(贪心)
2020-04-14 Codeforces Round #634 A. Candies and Two Sisters(水)
点击右上角即可分享
微信分享提示
主题色彩