[POJ1743]Musical Theme[SA+二分]

2009那篇论文里介绍的做法

这里面有下载链接

这个题是要转成差分序列再做的(同时要对答案处理一下)

导致我WA了一发的地方 if (Max - Min > x) return 1; 写成>=了(求最长不重叠重复子串确实是>=)

对于下面这两组数据

5
1 1 1 1 1
6
1 1 1 1 1 1

这两组数据在差分序列上的最长不重叠重复子串长度都是 2 ,但第一组的实际答案是 2 ,第二组是 3 ,所以要使得第一组二分出来的值是 1 (我输出的是二分的答案加 1 )

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int k, n, rnk[20005], sa[20005], s[20005], H[20005], c[20005];

void Sort(int *x, int *y, int *rk) {
  static int C[20005];
  for (int i = 0; i <= k; ++i) C[i] = 0;
  for (int i = 1; i <= n; ++i) ++C[rk[i]];
  for (int i = 1; i <= k; ++i) C[i] += C[i - 1];
  for (int i = n; i; --i) y[C[rk[x[i]]]--] = x[i];
}
inline bool cmp(int *y, int a, int b, int m) {return y[a] == y[b] && y[a + m] == y[b + m];}
void get_SA() {
  static int Y[20005];
  int *y = Y, *rk = rnk;
  k = 200;
  for (int i = 1; i <= n; ++i) rk[i] = s[y[i] = i];
  Sort(y, sa, rk);
  for (int m = 1, p = 0; p < n; k = p, m <<= 1) {
    for (p = 0; p < m; ++p) y[p + 1] = n - m + p + 1;
    for (int i = 1; i <= n; ++i)
      if (sa[i] > m) y[++p] = sa[i] - m;
    Sort(y, sa, rk), swap(y, rk);
    rk[sa[p = 1]] = 1;
    for (int i = 2; i <= n; ++i) rk[sa[i]] = cmp(y, sa[i - 1], sa[i], m) ? p : ++p;
  }
  for (int i = 1; i <= n; ++i) rnk[sa[i]] = i;
}

void get_H() {
  for (int i = 1, k = 0; i <= n; H[rnk[i++]] = k)
    for (k ? --k : 0; s[i + k] == s[sa[rnk[i] - 1] + k]; ++k);
}

bool check(int x) {
  for (int i = 2, Min = sa[1], Max = sa[1]; i <= n; ++i) {
    if (H[i] >= x) Min = min(Min, sa[i]), Max = max(Max, sa[i]);
    else Max = Min = sa[i];
    if (Max - Min > x) return 1;
  }
  return 0;
}

int main() {
  while (~scanf("%d", &n) && n) {
    for (int i = 1; i <= n; ++i) scanf("%d", c + i), s[i] = c[i] - c[i - 1] + 90;
    get_SA();
    get_H();
    int l = 1, r = n, mid;
    while (l <= r) {
      if (check(mid = l + r >> 1)) l = mid + 1;
      else r = mid - 1;
    }
    cout << (l < 5 ? 0 : l) << endl;//l-1<4?0:l-1+1
  }
  return 0;
}
posted @ 2019-03-26 22:18 QvvQ 阅读(...) 评论(...) 编辑 收藏