HDU 6208 (字符串hash)

Posted Jstyle - 急功近利不可成,踏踏实实才是真

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 6208 (字符串hash)相关的知识,希望对你有一定的参考价值。

题目链接: http://acm.split.hdu.edu.cn/showproblem.php?pid=6208

题意:给你n个串,能不能在这n个串中找到一个串,使得其它所有的串都是这个串的子串。

题解:找到最长的串作为主串,将主串hash一下,然后去匹配其它串即可

代码:

技术分享
 1 #pragma GCC diagnostic error "-std=c++11"
 2 #include <bits/stdc++.h>
 3 using namespace std;
 4 #define mem(a,b) memset(a,b,sizeof(a))
 5 #define FIN freopen("in.txt","r",stdin)
 6 #define IO ios_base::sync_with_stdio(0),cin.tie(0)
 7 #define pb push_back
 8 typedef long long LL;
 9 typedef unsigned long long ULL;
10 typedef pair<int, int> PIR;
11 
12 const int MAXN = 1e5+5;
13 
14 int T, n;
15 ULL H[MAXN], qpow[MAXN];
16 string S, s[MAXN];
17 map <ULL, bool> vis;
18 
19 void pre () {
20     qpow[0] = 1;
21     for (int i = 1; i <= 1e5; ++i) qpow[i] = qpow[i-1]*27;
22 }
23 ULL getHash (int l, int r) {
24     if (l == 0) return H[r];
25     else return (H[r]-H[l-1]*qpow[r-l+1]);
26 }
27 void solve () {
28     H[0] = S[0]-a+1;
29     for (int i = 1; i < S.size(); ++i) H[i] = H[i-1]*27+S[i]-a+1;
30 
31     for (int i = 1; i <= n; ++i) {
32         if (s[i] == S) continue;
33         ULL e = s[i][0]-a+1, e1 = S[0]-a+1;
34         for (int j = 1; j < s[i].size(); ++j) e = e*27+s[i][j]-a+1;
35         int ok = 0;
36         for (int j = 0; j < S.size(); ++j) {
37             if (j+s[i].size()-1 >= S.size()) break;
38             ULL x = getHash(j, j+s[i].size()-1);
39             if (x == e) {
40                 ok = 1;
41                 break;
42             }
43         }
44         if (!ok) {
45             cout << "No" << endl;
46             return ;
47         }
48     }
49     cout << S << endl;
50 }
51 int main ()
52 {IO;
53     //FIN;
54     pre();
55     cin >> T;
56     while (T--) {
57         vis.clear();
58         cin >> n;
59         int maxn = 0, id = -1;
60         for (int i = 1; i <= n; ++i) {
61             cin >> s[i];
62             if (s[i].size() > maxn) {
63                 maxn = s[i].size();
64                 id = i;
65             }
66         }
67         S = s[id];
68         solve();
69     }
70     return 0;
71 }
View Code

 

以上是关于HDU 6208 (字符串hash)的主要内容,如果未能解决你的问题,请参考以下文章

HDU–6208 The Dominator of Strings[KMP]

hdu-4300(字符串hash)

HDU 4821 String 字符串hash

HDU 4821 String (HASH)

HDU 4821 2013长春现场赛hash

HDU 5782 Cycle(KMP+Hash)