UVA 12338,uva12338

來源:互聯網
上載者:User

UVA 12338,uva12338
UVA 12338 - Anti-Rhyme Pairs

題目連結

題意:給定一些字串,每次詢問求出兩個字串的最長公用首碼的長度

思路:把字串排序,就能求出height和rank數組,然後利用RMQ查詢即可

代碼:

#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;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.