[NOI2016]优秀的拆分

嘟嘟嘟


这题不得不吐槽一下,\(O(n ^ 2)\)哈希能得95分,那么考场上有人写正解吗?或许只有队爷儿吧


正解思路特别妙,这篇题解也很妙:题解:[NOI2016]优秀的拆分(洛谷第一篇题解,带图的那个)。
我这绝对不是在水博客,因为那篇题解讲的太清楚了,我都不知道补充啥好。


然后因为\(n\)不是很大,所以找lcp和lcs的时候可以\(O(logn)\)用哈希二分,总复杂度\(O(n log ^ 2n)\)。(毕竟我不会SA也不想写SAM)。


还有,第13个点最后一组数据卡自然溢出哈希,得换成取模版哈希或双哈希(就是写一个自然溢出和一个取模,判等的话必须这两者都相等才算相等)

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
#include<ctime>
#include<cassert>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e6 + 5;
const ll BAS = 31;
const ll mod = 998244353;
In ll read()
{
  ll ans = 0;
  char ch = getchar(), last = ' ';
  while(!isdigit(ch)) last = ch, ch = getchar();
  while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
  if(last == '-') ans = -ans;
  return ans;
}
In void write(ll x)
{
  if(x < 0) x = -x, putchar('-');
  if(x >= 10) write(x / 10);
  putchar(x % 10 + '0');
}

char s[maxn];
int n;
ll has[maxn], p[maxn];
ll Beg[maxn], End[maxn];

In ll H(int L, int R) {return (has[R] - has[L - 1] * p[R - L + 1] % mod + mod) % mod;}
In int lcs(int x, int y)
{
  int L = 0, R = x;
  while(L < R)
    {
      int mid = (L + R + 1) >> 1;
      if(H(x - mid + 1, x) == H(y - mid + 1, y)) L = mid;
      else R = mid - 1;
    }
  return L;
}
In int lcp(int x, int y)
{
  int L = 0, R = n - y + 1;
  while(L < R)
    {
      int mid = (L + R + 1) >> 1;
      if(H(x, x + mid - 1) == H(y, y + mid - 1)) L = mid;
      else R = mid - 1;
    }
  return L;
}
In void solve(int len)
{
  for(int i = len; i <= n; i += len)
    {
      int j = i + len;
      if(j > n) break;
      int l1 = min(len, lcs(i, j)), l2 = min(len, lcp(i, j));
      if(l1 + l2 >= len + 1)
	{
	  int tp = l1 + l2 - len - 1;
	  ++Beg[i - l1 + 1], --Beg[i - l1 + 1 + tp + 1];
	  ++End[j + l2 - 1 - tp], --End[j + l2];
	}
    }
}

In void init()
{
  Mem(Beg, 0), Mem(End, 0);
  for(int i = 1; i <= n; ++i) has[i] = (has[i - 1] * BAS + s[i] - 'a') % mod;
}

int main()
{
  //freopen("ha.in", "r", stdin);
  int T = read();
  p[0] = 1;
  for(int i = 1; i < maxn; ++i) p[i] = p[i - 1] * BAS % mod;
  while(T--)
    {
      scanf("%s", s + 1);
      n = strlen(s + 1); init();
      for(int i = 1; i <= (n >> 1); ++i) solve(i);
      ll ans = 0;
      for(int i = 1; i <= n; ++i)
	{
	  Beg[i] = Beg[i - 1] + Beg[i];
	  End[i] = End[i - 1] + End[i];
	  ans += End[i - 1] * Beg[i];
	}
      write(ans), enter;
    }
  return 0;
}
posted @ 2019-05-07 20:12  mrclr  阅读(188)  评论(0编辑  收藏  举报