UVA 12338-anti-rhyme Pairs
Topic links
Test instructions: Given some strings, the length of the longest common prefix of two strings per query is calculated
Idea: Sort the strings, you can find the height and rank array, and then use the RMQ query to
Code:
#include <cstdio> #include <cstring> #include <iostream> #include <string> #include <
Algorithm> using namespace std;
const int N = 100005;
typedef pair<string, int> PII;
PII Str[n];
int save[n];
int T, N, Height[n], rank[n];
void Init () {scanf ("%d", &n);
for (int i = 0; i < n; i++) {cin >> Str[i].first;
Save[i] = Str[i].first.length ();
Str[i].second = i;
} sort (str, str + n);
for (int i = 0; i < n; i++) {Rank[str[i].second] = i;
if (i = = 0) continue;
int len = min (Str[i-1].first.length (), str[i].first.length ());
Int J;
for (j = 0; J < Len; J + +) {if (str[i-1].first[j]! = Str[i].first[j]) break;
} Height[i] = j;
}} int best[n * 10][20];
void Initrmq () {for (int i = 0; i < n; i++) best[i][0] = Height[i]; for (int j = 1; (1<<j) <= N; J + +) for (int i = 0; i + (1<<j)-1 < n; i++) best[i][j] = min (best[i][j-1], Best[i + (1<< (j-1))] [J-1]); } int LCP (int L, int R) {l--;
r--;
if (L = = R) return save[l]; L = Rank[l];
R = Rank[r];
if (L > R) Swap (L, R);
l++;
int k = 0;
while ((1<< (k + 1)) <= R-l + 1) k++;
return min (best[l][k], best[r-(1<<k) + 1][k]);
} int main () {int cas = 0;
scanf ("%d", &t);
while (t--) {init ();
INITRMQ ();
int Q, L, R;
scanf ("%d", &q);
printf ("Case%d:\n", ++cas);
while (q--) {scanf ("%d%d", &l, &r);
printf ("%d\n", LCP (L, R));
}} return 0; }