HDU 2609 How Many [最小表示法] [字符串处理]

来源:互联网 发布:linux 编译器gdb 编辑:程序博客网 时间:2024/06/06 04:21

How many
Time Limit: 1000MS Memory Limit: 32768KB 64bit IO Format: %I64d & %I64u

Description
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


裸题存板。

#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<vector>#include<queue>#include<stack>#include<map>#include<set>#include<string>#include<iomanip>#include<ctime>#include<climits>#include<cctype>#include<algorithm>#ifdef WIN32#define AUTO "%I64d"#else#define AUTO "%lld"#endifusing namespace std;#define smax(x,tmp) x=max((x),(tmp))#define smin(x,tmp) x=min((x),(tmp))#define maxx(x1,x2,x3) max(max(x1,x2),x3)#define minn(x1,x2,x3) min(min(x1,x2),x3)const int INF=0x3f3f3f3f;const int maxn = 10005;const int maxl = 105;char s[maxn][maxl];int head[maxn];int n;int min_present(char ss[maxl]){    int lens = strlen(ss);    int i=0,j=1;    while(i<lens && j<lens)    {        int k=0;        while(ss[(i+k)%lens]==ss[(j+k)%lens] && k<=lens) k++; // must check to break!!        if(k>=lens) break; // case of exactly equality        if(ss[(i+k)%lens]<ss[(j+k)%lens]) i+=k+1;        else j+=k+1;        if(i==j) j++;    }    return min(i,j);}inline bool init(){    if(!~scanf("%d",&n)) return false;    for(int i=1;i<=n;i++) scanf("%s",s+i);    for(int i=1;i<=n;i++) head[i]=min_present(s[i]);    return true;}struct Hash{    unsigned hash1,hash2;    bool operator < (const Hash t) const    {        if(hash1^t.hash1) return hash1 < t.hash1;        else return hash2 < t.hash2;    }    bool operator == (const Hash t) const { return hash1==t.hash1 && hash2==t.hash2; }}_hash[maxn];int work(){    memset(_hash,0,sizeof(_hash));    for(int i=1;i<=n;i++)    {        char *ss = s[i];        int lens = strlen(ss);        unsigned &t1 = _hash[i].hash1 , &t2 = _hash[i].hash2;        for(int j=head[i];;j=(j+1)%lens)        {            t1 = (t1<<5) ^ (t1>>27) ^ ss[j];            t2 = (t2<<7) ^ (t2>>25) ^ ss[j];            if(j == (head[i]-1+lens)%lens) break;        }    }    sort(_hash+1,_hash+n+1);    int tot = unique(_hash+1,_hash+n+1) - _hash - 1;    return tot;}int main(){    freopen("how.in","r",stdin);    freopen("how.out","w",stdout);    while(init())        printf("%d\n",work());    return 0;}
0 0
原创粉丝点击