首页 > 其他分享 >abc272_f Two Strings (后缀数组)

abc272_f Two Strings (后缀数组)

时间:2022-10-09 09:58:54浏览次数:79  
标签:cnt -- Two Strings abc272 sa include id

https://atcoder.jp/contests/abc272/tasks/abc272_f
将SS#TT在字符串中排序,看标号为1-n后面有多少2n + 2 - 3n + 1的标号
然后就会
image
注意题目要的是小于等于,那么要拼成 SS#TT| #和|在ascii码表中在小写字母两端。 这样保证两个字符串在比较完长度为n后S后面的#小于T中任意一个字符。

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int N = 1000010;

char s[N];
int n, sa[N], rk[N], oldrk[N << 1], id[N], px[N], cnt[N];

// px[i] = rk[id[i]](用于排序的数组所以叫 px)

bool cmp(int x, int y, int w) {
  return oldrk[x] == oldrk[y] && oldrk[x + w] == oldrk[y + w];
}
int suf[N];
int main() {
  int i, m = 300, p, w; // m是基数排序的值域
  scanf("%d", &n);
  scanf("%s", s + 1);


  for ( int i = n + 1; i <= n << 1; ++ i ) s[i] = s[i - n];
  s[n * 2 + 1] = '#';
  for ( int i = n * 2 + 2; i <= n * 2 + 1 + n; ++ i ) scanf(" %c", &s[i]);
  int tmp = n; n = n * 3 + 1; 
  for ( int i = n + 1; i <= n + tmp; ++ i ) s[i] = s[i - tmp];
  n += tmp; 
  s[n + 1] = '|'; ++ n;
  for (i = 1; i <= n; ++i) {
    ++cnt[rk[i] = s[i]];
  }
  for (i = 1; i <= m; ++i) cnt[i] += cnt[i - 1];
  for (i = n; i >= 1; --i) sa[cnt[rk[i]]--] = i;

  for (w = 1;; w <<= 1, m = p) {  // m=p 就是优化基数排序值域
    for (p = 0, i = n; i > n - w; --i) id[++p] = i; //计算按第二关键字排序下的第一关键字id[i]
    for (i = 1; i <= n; ++i)
      if (sa[i] > w) id[++p] = sa[i] - w;
    memset(cnt, 0, sizeof(cnt));
    for (i = 1; i <= n; ++i) ++cnt[px[i] = rk[id[i]]]; //在第二排的顺序的排第一编号
    for (i = 1; i <= m; ++i) cnt[i] += cnt[i - 1];
    for (i = n; i >= 1; --i) sa[cnt[px[i]]--] = id[i];
    memcpy(oldrk, rk, sizeof(rk));
    for (p = 0, i = 1; i <= n; ++i) // 去重
      rk[sa[i]] = cmp(sa[i], sa[i - 1], w) ? p : ++p;
    if (p == n) { //没有相同的,就确定出顺序了
      for (int i = 1; i <= n; ++i) sa[rk[i]] = i;
      break;
    }
  }

  for ( int i = 1; i <= n; ++ i ) {
    if(sa[i] > tmp * 2 + 1 && sa[i] <= tmp * 2 + 1 + tmp ) ++ suf[i];
  }
  long long ans = 0;
  for (i = n; i >= 1; --i) {
    suf[i] += suf[i + 1];

  }

  for ( int i = 1; i <= n; ++ i ) {
    if(sa[i] <= tmp) ans += suf[i];
  }
  cout << ans << '\n';
  return 0;
}

标签:cnt,--,Two,Strings,abc272,sa,include,id
From: https://www.cnblogs.com/muscletear/p/16771085.html

相关文章