codeforces 745/A Hongcow Learns the Cyclic Shift(字符串处理)(set的运用)

Hongcow学习了拼写新单词,通过循环移位单词的最后一个字母到开头,生成尽可能多的不同单词。本篇介绍如何使用数据结构解决这一问题,通过存储每次移位后的新单词到集合中,最终计算不同单词的数量。

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

Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.

Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word “abracadabra” Hongcow will get words “aabracadabr”, “raabracadab” and so on.

Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.

Input
The first line of input will be a single string s (1 ≤ |s| ≤ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters (‘a’–‘z’).

Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.

Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are “abcd”, “dabc”, “cdab”, and “bcda”.

For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate “bbb”.

For the third sample, the two strings Hongcow can generate are “yzyz” and “zyzy”.

题目链接

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

题目大意

已知一个字符串,每次将字符串最后一个字符提到最前面,包括原字符串问最多能组成多少个不同的字符串。

数据范围

s (1 ≤ |s| ≤ 50)
lowercase English letters (‘a’–‘z’).

解题思路

将每个新字符串存入set的中,因为它每个相同的字符串只会存一个。最后判断存入了多少个就行了。
小技巧
这道题可以把原字符串再抄一遍加在后面,用循环从第一个字符到原字符串最后一个字符每次往后截取原字符串的长度,这样就能得到每个新字符串

解决代码

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<set>
using namespace std;
set<string>aa;
int main()
{
string a;
int n ;
cin >> a;
n = a.size();
a = a + a;
for(int i = 0;i < n;i++){
	string b;
	for(int j = 0;j < n;j++){
		b += a[i + j];
		}
		aa.insert(b);
	}
	printf("%d\n",aa.size());
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值