1. 程式人生 > 實用技巧 >C Count New String

C Count New String

從後往前看,可以發現,當前字母是\(c\),當前位置\(p\),最多能影響到\(p'\),得到\([p,p']\)區間,把所有\(c\)字母影響區間合併在一起,可以得到\([L,R]<=[1,n]\),即每個字母最多影響長度為n的區間,所以我們把所以的字尾拿出來建立廣義字尾自動機(實際先建立tire樹)即可。

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<bitset>
#include<map>
//#include<regex>
#include<cstdio>
#include <iomanip>
#pragma GCC optimize(2)
#define up(i,a,b)  for(int i=a;i<b;i++)
#define dw(i,a,b)  for(int i=a;i>b;i--)
#define upd(i,a,b) for(int i=a;i<=b;i++)
#define dwd(i,a,b) for(int i=a;i>=b;i--)
//#define local
typedef long long ll;
typedef unsigned long long ull;
const double esp = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int inf = 1e9;
using namespace std;
ll read()
{
	char ch = getchar(); ll x = 0, f = 1;
	while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
	return x * f;
}
typedef pair<int, int> pir;
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lrt root<<1
#define rrt root<<1|1
const int N = 1e6 + 10;
struct exsam {
	int len[N << 1];
	int par[N << 1];
	int trans[N << 1][11]; int tot = 1;
	int work(int p, int c) {
		int newq = ++tot; int q = trans[p][c];
		len[newq] = len[p] + 1;
		par[newq] = par[q]; memcpy(trans[newq], trans[q], sizeof(trans[q]));
		par[q] = newq;
		for (; p&&trans[p][c] == q; p = par[p]) {
			trans[p][c] = newq;
		}
		return newq;
	}
	int ins(int p,int c)
	{
		if (trans[p][c])
		{
			int q = trans[p][c];
			if (len[p] + 1 == len[q])return q;
			else return work(p, c);
		}
		else {
			int now = ++tot;
			len[now] = len[p] + 1;
			for (; p && !trans[p][c]; p = par[p])
				trans[p][c] = now;
			if (!p) {
				par[now] = 1;
			}
			else {
				int q = trans[p][c]; 
				if (len[q] == len[p] + 1)par[now] = q;
				else par[now] = work(p, c);
			}
			return now;
		}
	}
}sam;
char s[N];
stack<pir>st;
int pos[N];
int main()
{
	scanf("%s", s + 1);
	int len = strlen(s + 1);
	st.push({ 11,len+1 });
	pos[len + 1] = 1;
	dwd(i, len, 1)
	{
		int c = s[i] - 'a';
		while (!st.empty() && st.top().first < c)st.pop();
		pir t = st.top();
		int last = pos[t.second];
		dwd(j,t.second-1, i)           
		{
			last = sam.ins(last, s[i] - 'a');
			pos[j] = last;
		}
		st.push({ s[i] - 'a',i });
	}
	ll ans = 0;
	upd(i, 2, sam.tot)
	{
		ans += sam.len[i] - sam.len[sam.par[i]];
	}
	cout << ans << endl;
}