-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1517_hash-binary_search_solution.cpp
More file actions
78 lines (67 loc) · 1.91 KB
/
1517_hash-binary_search_solution.cpp
File metadata and controls
78 lines (67 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//Task: find the largest common substring of two strings of the same length N. N <= 10^5, time limit 2 s, memory 64 MB.
//Solution: using polymial hashing with two modules, solve the problem using binary search.
#include <bits/stdc++.h>
#define int uint64_t
using namespace std;
const int mod = 1e9+7;
main()
{
int n;
cin >> n;
string a,b;
cin >> a >> b;
int p_ = 257;
vector<pair<int,int> > p(n,{1,1});
vector<pair<int,int> > a_pref(n);
vector<pair<int,int> > b_pref(n);
for(int i = 1; i < n; i++) {
p[i].first = (p[i-1].first*p_)%mod;
p[i].second = p[i-1].second*p_;
}
a_pref[0].first = a[0];
a_pref[0].second = a[0];
b_pref[0].first = b[0];
b_pref[0].second = b[0];
for(int i = 1; i < n; i++) {
a_pref[i].first = (a_pref[i-1].first*p_%mod + a[i])%mod;
b_pref[i].first = (b_pref[i-1].first*p_%mod + b[i])%mod;
a_pref[i].second = a_pref[i-1].second*p_ + a[i] + INT64_MAX;
b_pref[i].second = b_pref[i-1].second*p_ + b[i] + INT64_MAX;
}
int l = 0, r=n+1,pos=-1;
while(r-l > 1) {
int m = (r+l)/2;
map<pair<int,int>,int> mp;
bool f = 0;
for(int i = m-1; i < n; i++) {
// hash [i+1-m,i]
if(i==m-1) {
mp[{a_pref[i].first,a_pref[i].second}]++;
continue;
}
mp[{(a_pref[i].first-a_pref[i-m].first*p[m].first%mod + mod)%mod, (a_pref[i].second-a_pref[i-m].second*p[m].second) + INT64_MAX}]++;
}
for(int i = m-1; i < n; i++) {
if(i==m-1){
if(mp[{b_pref[i].first,b_pref[i].second}]) {
pos=i;
f=1;
break;
}
}
if(mp[{(b_pref[i].first-b_pref[i-m].first*p[m].first%mod + mod)%mod, (b_pref[i].second-b_pref[i-m].second*p[m].second) + INT64_MAX}]) {
pos = i;
f=1;break;
}
}
if(f) {
l = m;
}
else r = m;
}
if(l) {
for(int i=pos-l+1; i <= pos; i++) {
cout << b[i];
}
}
}