题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2609
题意:
给定n个01组成的字符串,每个字符串是一个环状的结构,求可以经过循环旋转,最后不同的串有多少个。
题解:
求出每个字符串的最小表示,然后求hash值,set去重即可。
AC代码:
#include<iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
using namespace std;
#define _for(i,a,b) for(int i=a;i<=b;i++)
const int maxn = 205;
const int mod = 1e9+7;
set<int> S;
int n;
long long ha[maxn];
int p = 123;
int minrepresstation(char *s)
{
int length = strlen(s);
int i=0,j=1,k=0;
while(i<length&&j<length&&k<length)
{
int now = s[(i+k)%length]-s[(j+k)%length];
if(now==0)k++;
else
{
if(now>0)i=i+k+1;
else j=j+k+1;
if(i==j)j++;
k=0;
}
}
return min(i,j);
}
int get_hash(char *s,int x,int y)
{
_for(i,0,y)ha[i]=0;
_for(i,0,y-1)ha[(i+x)%y]=(ha[(i-1+x)%y]*p+(int)(s[(i+x)%y]))%mod;
return (int)ha[(x-1+y)%y];
}
int main(int argc, char const *argv[])
{
while(scanf("%d",&n)!=EOF)
{
char s[maxn];
S.clear();
_for(i,1,n)
{
scanf("%s",s);
int now = strlen(s);
int k = minrepresstation(s);
S.insert(get_hash(s,k,now));
}
cout<<S.size()<<endl;
}
return 0;
}

博客给出题目链接,题目是给定n个由01组成的环状字符串,求经循环旋转后不同串的数量。题解为求出每个字符串的最小表示,再求hash值,用set去重。
1426

被折叠的 条评论
为什么被折叠?



