码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 6208 (字符串hash)

时间:2017-10-10 20:39:15      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:out   closed   define   题意   sign   pre   cin   std   ble   

题目链接: 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)

标签:out   closed   define   题意   sign   pre   cin   std   ble   

原文地址:http://www.cnblogs.com/Jstyle-continue/p/7647368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!