关于 hash 做法
查看原帖
关于 hash 做法
126972
Kevinx楼主2024/10/11 16:04

TLE * 2 + WA* 6

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e4+10;
ll base = 233, Mod = 1e9+7;
char s[25];
ll res = 0, a[N], id = 0, b[N], ans, len;
ll n, m, tot;
map<ll, ll> Map;
int main (){
	scanf("%lld%lld", &n, &m);
	for(int i = 1; i <= n; i++) {
		scanf("%s", s);
		res = 0, len = strlen(s);
		for(int j = 0; j < len; j++) res = (res*base+s[j])%Mod;
		Map[res] ++;
	}
	for(int i =1; i <= m; i++) {
		scanf("%s", s);
		tot = 0, ans = 0;
//		memset(a, 0, sizeof(a));
		res = 0, len = strlen(s);
		for(int j = 0; j < len; j++) res = (res*base+s[j])%Mod;
		if(Map.count(res) == 1) {
			puts("-1");
			continue;
		}
		for(int k = 0; k < len; k++) {
			for(int x = 0; x <= 25; x++){
				res = 0;
				char change = 'a'+x;
				for(int j = 0; j < len; j++) {
				if(j==k) res = (res*base+change)%Mod;
				else 	 res = (res*base+s[j])%Mod;
			}
			a[++tot] = res;
			
			res = 0;
			for(int j = 0; j < len; j++) {
				
				if(j==k) res = (res*base+change)%Mod;
						 res = (res*base+s[j])%Mod;
			}
			a[++tot] = res;
			}
			
			res = 0;
			for(int j = 0; j < len; j++) {
				
				if(j==k) continue;
				res = (res*base+s[j])%Mod;
			}
			a[++tot] = res;
			
		}
		for(int x = 0; x <= 25; x++){
			res = 0;
			char change = 'a'+x;
			for(int j = 0; j < len; j++) res = (res*base+s[j])%Mod;
			res = (res*base+change)%Mod;
			a[++tot] = res;
		}
		
		sort(a+1, a+tot+1);
		ll lengh = unique(a+1, a+tot+1)-a;
		
		for(int j = 1; j <= lengh; j++) {
			if(Map.count(a[j])== 1) ans+= Map[a[j]];
		}
		printf("%lld\n", ans);
	}
	return 0;
} 
/*
4 3
abcd
abcde
aabc
abced

abcd
abcd
abcdd
*/ 
2024/10/11 16:04
加载中...