题目链接:
http://codeforces.com/problemset/problem/770/A
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
- the length of the password must be equal to n,
- the password should consist only of lowercase Latin letters,
- the number of distinct symbols in the password must be equal to k,
- any two consecutive symbols in the password must be distinct.
Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions.
The first line contains two positive integers n and k (2 ≤ n ≤ 100, 2 ≤ k ≤ min(n, 26)) — the length of the password and the number of distinct symbols in it.
Pay attention that a desired new password always exists.
Print any password which satisfies all conditions given by Innokentiy.
4 3
java
6 6
python
5 2
phphp
题目大意:
有一个人想要换密码,让你帮助他找到一个新密码。密码满足四个条件:
1:长度为n;
2:都是小写英文字母;
3:不同字母的个数为k;
4:任何人相邻的字母不能相同。
解题思路:
因为题目说是输出任何一种满足题意的答案,所以问题就变简单了。就从字母‘a’开始,如果不同字母的个数没有达到k,那么输出‘b’,还没有达到输出‘c’......如果不同字母的个数达到k的话,就输出(char)(i%k+'a'),其中 i 为密码的第 i 位。如果看不懂就看一下代码,看完就懂了。
代码:
#include<iostream>
using namespace std;
int main()
{
int n,k;
while(cin>>n>>k)
{
for(int i=0;i<=n-1;i++) //控制长度为n
{
if(i>k-1) //如果if条件成立,说明字母不同字母个数已达到k个,下一个字母要重新从‘a’开始
cout<<(char)(i%k+'a');
else //不同字母个数还没有达到k,那么继续按照顺序写下一个字符
cout<<(char)(i+'a');
}
cout<<endl;
}
return 0;
}