Give you n ( n < 10000) necklaces ,the length of necklace will not large than 100,tell me
How many kinds of necklaces total have.(if two necklaces can equal by rotating ,we say the two necklaces are some).
For example 0110 express a necklace, you can rotate it. 0110 -> 1100 -> 1001 -> 0011->0110.
How many kinds of necklaces total have.(if two necklaces can equal by rotating ,we say the two necklaces are some).
For example 0110 express a necklace, you can rotate it. 0110 -> 1100 -> 1001 -> 0011->0110.
InputThe input contains multiple test cases.
Each test case include: first one integers n. (2<=n<=10000)
Next n lines follow. Each line has a equal length character string. (string only include '0','1').
OutputFor each test case output a integer , how many different necklaces.Sample Input
Each test case include: first one integers n. (2<=n<=10000)
Next n lines follow. Each line has a equal length character string. (string only include '0','1').
OutputFor each test case output a integer , how many different necklaces.Sample Input
4
0110
1100
1001
0011
4
1010
0101
1000
0001
Sample Output
1
2 本来是各种找特征,然后扩展kmp判,但是找不到,看了题解。学习了最小字符串 s=“bbaa” 经过循环能够得到4个同构字符串, 其中最小的是 “aabb” 如何求最小字符串 i=0, j=1, k=0 如果 s[i] < s[j] 很容易理解 j++;
如果 s[i] > s[j] 也很好理解 i=j;
如果 s[i] == s[j] ,
可以令 k=0, 在i和j之间 找到 第一个s[i+k] != s[j+k]的位置
如果 s[i+k] < s[j+k] 说明i~i+k 都符合,所以 j=j+k+1
如果 s[i+k] > s[j+k] 说明i-i+k 都不符合, 所以 i=i+k+1 两个注意事项:
第一: i和j不能相等
第二: 每次s[i] != s[j] ,k=0
#include<stdio.h>
#include<string.h>
#include<string>
#include<set>
#include<algorithm>
using namespace std;
set<string> ss;
int n,len;
char s[],t[]; //最小字符串模板
int minstring(char* s) {
int i=,j=,k=;
while(i<len&&j<len&&k<len) {
int tmp=s[(i+k)%len]-s[(j+k)%len];
if(!tmp) k++;
else {
if(tmp<) {
j+=k+;
} else {
i+=k+;
}
if(i==j) j++;
k=;
}
}
return min(i,j);
} void getstring(char* str) {//写法很厉害
str[len/]='\0';
ss.insert(str); //竟然还能这样
} int main() {
while(~scanf("%d",&n)) {
for(int i=;i<n;i++) {
scanf("%s",t);
strcpy(s,t);
strcat(s,t);
len=strlen(s);
int k=minstring(s);//得到最小字符串的起始位置
getstring(s+k);
}
printf("%d\n",ss.size());
ss.clear();
}
}