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.
Input
The 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’).
Output
For 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
题解:
对每个字符串求出它的最小表示法。放入set去重。
输出set的size值即可。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <set>
#include <string>
using namespace std;
//最小表示法
int get_minstring(string s)
{
int len = s.length();
int i = 0, j = 1, k = 0;
while(i<len && j<len && k<len)
{
int t=s[(i+k)%len]-s[(j+k)%len];
if(t==0)
k++;
else
{
if(t > 0)
i+=k+1;
else
j+=k+1;
if(i==j) j++;
k=0;
}
}
return min(i,j);
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
set<string> s;
string str;
for(int i=0;i<n;i++)
{
cin>>str;
int mini = get_minstring(str);
str=str.substr(mini)+str.substr(0,mini);
s.insert(str);
}
cout<<s.size()<<endl;
}
return 0;
}