links
UVA 12338 Test Instructions
For each case, give n Words (strings), followed by a Q group asking, for each set of queries (I, j), given the longest common prefix length of the I string and the J string. Ideas
This is a typical string hash problem. The string has good monotonicity, which can be used to improve the efficiency by combining two points on the matching problem. For example, to find the two longest common prefix of the string, if the prefix J matches, then the prefix I (i < j) must be matched, using two points can quickly find the longest matching length.
The way to do this is to each string to the prefix hash array, for each query two points to find.
The code uses a natural overflow hash, but it is not stuck out. Code
#include <cstdio> #include <iostream> #include <vector> #include <cstring> #include <string&
Gt
using namespace Std;
typedef unsigned long long ulint;
#define MAXN (1000007) const ulint seed = 30007uLL;
Const Ulint mod = 1e9 + 1017uLL;
Ulint HI[MAXN], HJ[MAXN];
String WORD[MAXN];
Vector<ulint> H[MAXN];
int solve (int i, int j) {int ans = 0, L = 1, r = min (Word[i].size (), Word[j].size ()), m;
Vector<ulint> &hi = H[i];
Vector<ulint> &hj = H[j];
while (L <= r) {m = (L + r) >> 1;
if (hi[m-1] = = Hj[m-1]) {ans = m;
L = m + 1;
} else R = m-1;
} return ans;
} int main () {//freopen ("12338.txt", "R", stdin);
Cin.sync_with_stdio (FALSE);
int T, Kase = 0;
Cin >> T;
while (t--) {printf ("Case%d:\n", ++kase);
int N;
Cin >> N;
for (int i = 1; I <= N; i++) { CIN >> Word[i];
string& s = word[i];
vector<ulint>& h = h[i];
H.clear ();
H.push_back (S[0]-' a ' + 1);
for (int j = 1; J < S.size (); j + +) {h.push_back (h[j-1] * seed + s[j]-' a ' + 1);
}} int Q, I, J;
Cin >> Q;
while (q--) {cin >> i >> J;
printf ("%d\n", Solve (I, j));
}} return 0;
}