照着题解写了一份单hash疯狂错 不知道是哪个地方出问题了 求教
查看原帖
照着题解写了一份单hash疯狂错 不知道是哪个地方出问题了 求教
802370
waibibabu11楼主2023/8/2 17:19

照着题解写了一份单hash疯狂错 不知道是哪个地方出问题了 求教 我的代码

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef  unsigned long long ull;
int base=233;
int prime=233317;
ull m=212370440130137957;
ull harsh(char* s){
	int i;
	ull ans=0;
	int len=strlen(s);
	for(i=0;i<len;i++){
		ans=ans*base+(ull)s[i];
	}
	return ans;
}
int cmp(const void *a ,const void * b){
	return *((int *)a)-*((int *)b);
}
char s[1505];
int a[10005];
int main(){
	int n;
	scanf("%d",&n);
	int i;
	
	for(i=0;i<n;i++){
		scanf("%s",s);
		a[i]=harsh(s);
	}
	int ans=1;
	qsort(a,n,sizeof(a[0]),cmp);
	for(i=1;i<n;i++){
		if(a[i-1]!=a[i]){
			ans++;
		}
	}
	printf("%d",ans);
	return 0;
}

题解代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll int
#define inf 1<<30
#define mt(x,y) memset(x,y,sizeof(x))
#define il inline 
#define ull unsigned long long
il ll max(ll x,ll y){return x>y?x:y;}
il ll min(ll x,ll y){return x<y?x:y;}
il ll abs(ll x){return x>0?x:-x;}
il ll swap(ll x,ll y){ll t=x;x=y;y=t;}
il void read(ll &x){
    x=0;ll f=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')f=-f;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    x*=f;
}
using namespace std;
#define N 10001
#define base 233
ull mod=212370440130137957ll;
ll f[N],n;
char a[N];
ull hash(char s[]){
    ull ans=0,len=strlen(s);
    for(ll i=0;i<len;i++){
        ans=base*ans+(ull)s[i];
        //这里不使用mod让它自然溢出,定义为ull的数在超过2^32的时候会自然溢出
        //如果把这个换成上面的hash就会400ms+
        //所以说自然溢出大法好
    }
    return ans;
}
int main(){
    read(n);
    for(ll i=1;i<=n;i++){
        scanf("%s",a);
        f[i]=hash(a);
    }
    sort(f+1,f+n+1);ll ans=1;
    for(ll i=1;i<n;i++){
        if(f[i]!=f[i+1])ans++;
    }
    printf("%d\n",ans);
    return 0;
}
2023/8/2 17:19
加载中...