New Password (Codeforces-770A)

本文介绍 CodeForces 上 A.NewPassword 的解题思路与实现代码。题目要求生成长度为 n 的密码,包含 k 种不同的小写字母,且相邻字母不相同。文章提供了简单易懂的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

http://codeforces.com/problemset/problem/770/A

A. New Password
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

The first line contains two positive integers n and k (2 ≤ n ≤ 1002 ≤ 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.

Output

Print any password which satisfies all conditions given by Innokentiy.

Examples
input
4 3
output
java
input
6 6
output
python
input
5 2
output
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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值