[HAOI 2016]找相同字符
Posted navi-awson
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[HAOI 2016]找相同字符相关的知识,希望对你有一定的参考价值。
Description
给定两个只含小写字母字符串 (s_1,s_2) ,求出在两个字符串中各取出一个子串使得这两个子串相同的方案数。两个方案不同当且仅当这两个子串中有一个位置不同。
(1leq |s_1|,|s_2|leq 200000)
Solution
把两个串拼在一起,然后扫两遍。
第一遍统计所有的 (B) ,在它前面的 (A) 的贡献;第二遍统计所有的 (A) ,在它前面的 (B) 的贡献;
用单调栈维护一下即可。
Code
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = (200000+5)<<1;
char ch[N];
int s1, n, m, x[N<<1], y[N<<1], c[N], sa[N], rk[N], height[N];
ll ans, sum[N], a[N];
int s[N], top;
void get() {
for (int i = 1; i <= n; i++) c[x[i] = ch[i]]++;
for (int i = 2; i <= m; i++) c[i] += c[i-1];
for (int i = n; i >= 1; i--) sa[c[x[i]]--] = i;
for (int k = 1; k <= n; k <<= 1) {
int num = 0;
for (int i = n-k+1; i <= n; i++) y[++num] = i;
for (int i = 1; i <= n; i++) if (sa[i] > k) y[++num] = sa[i]-k;
for (int i = 1; i <= m; i++) c[i] = 0;
for (int i = 1; i <= n; i++) c[x[i]]++;
for (int i = 2; i <= m; i++) c[i] += c[i-1];
for (int i = n; i >= 1; i--) sa[c[x[y[i]]]--] = y[i];
swap(x, y); x[sa[1]] = num = 1;
for (int i = 2; i <= n; i++)
x[sa[i]] = (y[sa[i]] == y[sa[i-1]] && y[sa[i]+k] == y[sa[i-1]+k]) ? num : ++num;
if ((m = num) == n) break;
}
for (int i = 1; i <= n; i++) rk[sa[i]] = i;
for (int i = 1, k = 0; i <= n; i++) {
if (rk[i] == 0) continue;
if (k) k--; int j = sa[rk[i]-1];
while (i+k <= n && j+k <= n && ch[i+k] == ch[j+k]) ++k;
height[rk[i]] = k;
}
}
void cal(int ss) {
top = 0;
for (int i = 1; i <= n; i++) sum[i] = sum[i-1]+(ss == (sa[i] > s1) && sa[i] != s1+1);
for (int i = 1; i <= n; i++) {
while (top && height[s[top]] >= height[i]) --top;
s[++top] = i; a[top] = a[top-1]+(sum[i-1]-sum[s[top-1]-1])*height[i];
if (ss == (sa[i] <= s1) && sa[i] != s1+1) ans += a[top];
}
}
void work() {
scanf("%s", ch+1); s1 = strlen(ch+1);
ch[s1+1] = '$'; scanf("%s", ch+s1+2);
n = strlen(ch+1); m = 255; get();
cal(0), cal(1); printf("%lld
", ans);
}
int main() {work(); return 0; }
以上是关于[HAOI 2016]找相同字符的主要内容,如果未能解决你的问题,请参考以下文章