• Luogu P3370 【模板】字符串哈希


    gate

    对于每一位(s[i])
    (ans = (ans*base + (ull)s[i])\%mod + prime)

    建议数值
    (base = 131\ prime = 233317\ mod1 = 19260817\ mod2 = 20031101)

    • 双哈希
    #include<cstdio>
    #include<iostream>
    #include<cmath>
    #include<cstring>
    #include<algorithm>
    #define MogeKo qwq
    #define ull unsigned long long
    using namespace std;
    
    ull base = 131;
    struct node {
    	ull x,y;
    	bool operator < (const node &N)const {
    		return x<N.x || ((x==N.x) && (y<N.y));
    	}
    } a[10010];
    char s[10010];
    
    int n,ans;
    int prime = 233317;
    ull mod1 = 19260817;
    ull mod2 = 20031101;
    
    ull hash1(char s[]) {
    	int len = strlen(s);
    	ull ans = 0;
    	for(int i = 0; i < len; i++)
    		ans = (ans*base + (ull)s[i])%mod1 + prime;
    	return ans;
    }
    
    ull hash2(char s[]) {
    	int len = strlen(s);
    	ull ans = 0;
    	for(int i = 0; i < len; i++)
    		ans = (ans*base + (ull)s[i])%mod2 + prime;
    	return ans;
    }
    
    int main() {
    	scanf("%d",&n);
    	for (int i = 1; i <= n; i++) {
    		scanf("%s",s);
    		a[i].x = hash1(s);
    		a[i].y = hash2(s);
    	}
    	sort(a+1,a+n+1);
    	ans = 1;
    	for(int i = 1; i < n; i++) {
    		if(a[i].x != a[i+1].x || a[i].y != a[i+1].y)
    			ans++;
    	}
    	printf("%d
    ",ans);
    	return 0;
    }
    
    • 单哈希
    #include<cstdio>
    #include<iostream>
    #include<cmath>
    #include<cstring>
    #include<algorithm>
    #define MogeKo qwq
    #define ull unsigned long long
    using namespace std;
    
    ull base = 131;
    ull a[10010];
    char s[10010];
    int n,ans;
    int prime = 233317;
    ull mod = 212370440130137957ll;
    
    ull hashi(char s[]){
    	int len = strlen(s);
    	ull ans = 0;
    	for(int i = 0;i < len;i++)
    		ans = (ans*base + (ull)s[i])%mod + prime;
    	return ans;
    }
    
    int main() {
    	scanf("%d",&n);
    	for(int i = 1; i <= n; i++) {
    		scanf("%s",s);
    		a[i] = hashi(s);
    	}
    	sort(a+1,a+n+1);
    	ans = 1;
    	for(int i = 1; i < n; i++) {
    		if(a[i] != a[i+1])
    			ans++;
    	}
    	printf("%d",ans);
    }
    
  • 相关阅读:
    一致性算法—Paxos、Raft、ZAB
    分布式系统
    Alibaba开源组件-分布式流量控制框架sentinel初探
    Sentinel基本使用--基于QPS流量控制(二), 采用Warm Up预热/冷启动方式控制突增流量
    LinkedList实现基于LRU算法的缓存
    使用jdbc操作ClickHouse
    如何在js里引用php变量
    微信WeixinJSBridge API使用实例
    微信内置浏览器私有接口WeixinJSBridge介绍
    如何实现php手机短信验证功能
  • 原文地址:https://www.cnblogs.com/mogeko/p/13274170.html
Copyright © 2020-2023  润新知