A. Polo the Penguin and Strings

本文解决了一个问题:对于给定的字符串长度n和唯一字符数k,找到满足条件的最小字典序字符串,或者确认不存在这样的字符串。通过贪心策略实现,确保每个字符与其相邻字符不同,且最终字符串按字典序排序。

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Little penguin Polo adores strings. But most of all he adores strings of length n.

One day he wanted to find a string that meets the following conditions:

  1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.
  2. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds,si ≠ si + 1(1 ≤ i < n).
  3. Among all strings that meet points 1 and 2, the required string is lexicographically smallest.

Help him find such string or state that such string doesn't exist.

String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.

Input

A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters.

Output

In a single line print the required string. If there isn't such string, print "-1" (without the quotes).

Sample test(s)
input
7 4
output
ababacd
input
4 7
output
-1

解题说明:此题是一道典型的贪心问题,既要保证字符串中任意两个连续字符串不同,也要保证字典序最小,最简单的想法是只用a,b交替,在最后补上其他字符串即可。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include <algorithm>
#include<cstring>
#include<string>
using namespace std;

int main()
{
	int n, k, c, r, i;
	scanf("%d%d", &n, &k);
	if (k == n&&k <= 26)
	{
		c = 'a';
		for (i = 0; i<k; i++)
		{
			printf("%c", c + i);
		}
		printf("\n");
	}
	else if (k>n || k == 1)
	{
		printf("-1\n");
	}
	else
	{
		for (i = 0; i<n - (k - 2); i++)
		{
			if (i % 2 == 0)
			{
				printf("a");
			}
			else
			{
				printf("b");
			}
		}
		r = 2; 
		c = 'a';
		for (i; i < n; i++, r++)
		{
			printf("%c", c + r);
		}
		printf("\n");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值