首页 > 代码库 > hash练习

hash练习

/*poj 1200 Crazy Search 字符串hash O(n)枚举起点然后O(1)查询子串hash值然后O(n)找不一样的个数复杂度是线性的 */#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#define P 29#define maxn 1000010using namespace std;int n,c,len,p[maxn],ha[maxn],tot,hash[maxn],ans;char s[maxn];void Get_p(){    p[0]=1;    for(int i=1;i<=n;i++)        p[i]=p[i-1]*P;}void Get_ha(){    len=strlen(s+1);    for(int i=1;i<=len;i++)        ha[i]=ha[i-1]*P+s[i]-a;}int Query(int l,int r){    return ha[r]-ha[l-1]*p[r-l+1];}void Solve(){    for(int l=1;l+n-1<=len;l++){        int r=l+n-1;            hash[++tot]=Query(l,r);    }    sort(hash+1,hash+1+tot);    for(int i=1;i<=tot;i++)        if(hash[i]!=hash[i-1])ans++;}int main(){    scanf("%d%d%s",&n,&c,s+1);    Get_p();Get_ha();Solve();    printf("%d\n",ans);    return 0;}
/*poj 2503 Babelfish */#include<iostream>#include<cstdio>#include<cstring>#define maxn 100010#define P 19#define mod 10007using namespace std;int head[maxn],num;struct node{    int pre;    char v[110],u[110];}e[maxn*2];char lan[maxn][110],s[210];int Get(char *a){    int r=0,len=strlen(a);    for(int i=0;i<len;i++){        r=r*P+a[i]-a;r%=mod;    }    return r;}void Insert(char *a,char *b){    int x=Get(a);    num++;e[num].pre=head[x];    strcpy(e[num].v,b);    strcpy(e[num].u,a);    head[x]=num;}int find(char *a){    int x=Get(a);    for(int i=head[x];i;i=e[i].pre)        if(!strcmp(e[i].u,a)){            puts(e[i].v);            return 1;        }    return 0;}int main(){    while(1){        gets(s);        if(s[0]==\0)break;        int len=strlen(s),l1=-1,l2=-1,k;        char a[110],b[110];        memset(a,0,sizeof(a));        memset(b,0,sizeof(b));        for(int i=0;i<len;i++)            if(s[i]== ){k=i+1;break;}            else a[++l1]=s[i];        for(int i=k;i<len;i++)            b[++l2]=s[i];        Insert(b,a);    }    while(~scanf("%s",s)){        int p=find(s);        if(!p)printf("eh\n");    }    return 0;}

 

hash练习