[BZOJ3879]SvT

bzoj

sol

只要把输入的后缀按\(Rank\)排个序,相邻的之间求个\(lcp\),然后用单调栈维护一下即可。
可以作为单调栈的练手题。
剩下的就全是板子了。

code

#include<cstdio>
#include<algorithm>
using namespace std;
#define ll long long
int gi()
{
    int x=0,w=1;char ch=getchar();
    while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
    if (ch=='-') w=0,ch=getchar();
    while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
    return w?x:-x;
}
const ll mod = 23333333333333333;
const int N = 5e5+5;
char s[N];
int n,m,k,a[N],t[N<<3],x[N],y[N],SA[N],Rank[N],Height[22][N],lg[N],q[N],w[N];
ll ans,sum;
bool cmp(int i,int j,int k){return y[i]==y[j]&&y[i+k]==y[j+k];}
void getSA()
{
	int m=30;
    for (int i=1;i<=n;++i) ++t[x[i]=a[i]];
    for (int i=1;i<=m;++i) t[i]+=t[i-1];
    for (int i=n;i>=1;--i) SA[t[x[i]]--]=i;
    for (int k=1;k<=n;k<<=1)
    {
        int p=0;
        for (int i=0;i<=m;++i) y[i]=0;
        for (int i=n-k+1;i<=n;++i) y[++p]=i;
        for (int i=1;i<=n;++i) if (SA[i]>k) y[++p]=SA[i]-k;
        for (int i=0;i<=m;++i) t[i]=0;
        for (int i=1;i<=n;++i) ++t[x[y[i]]];
        for (int i=1;i<=m;++i) t[i]+=t[i-1];
        for (int i=n;i>=1;--i) SA[t[x[y[i]]]--]=y[i];
        swap(x,y);
        x[SA[1]]=p=1;
        for (int i=2;i<=n;++i) x[SA[i]]=cmp(SA[i],SA[i-1],k)?p:++p;
        if (p>=n) break;m=p;
    }
	for (int i=1;i<=n;++i) Rank[SA[i]]=i;
	for (int i=1,j=0;i<=n;++i)
	{
		if (j) --j;
		while (a[i+j]==a[SA[Rank[i]-1]+j]) ++j;
		Height[0][Rank[i]]=j;
	}
	for (int i=2;i<=n;++i) lg[i]=lg[i>>1]+1;
	for (int j=1;j<22;++j)
		for (int i=1;i+(1<<j-1)<=n;++i)
			Height[j][i]=min(Height[j-1][i],Height[j-1][i+(1<<j-1)]);
}
bool cmp_rank(int i,int j){return Rank[i]<Rank[j];}
int lcp(int i,int j)
{
	int l=Rank[i],r=Rank[j];
	++l;int k=lg[r-l+1];
	return min(Height[k][l],Height[k][r-(1<<k)+1]);
}
int main()
{
	n=gi();m=gi();scanf("%s",s+1);
	for (int i=1;i<=n;++i) a[i]=s[i]-'a'+1;
	getSA();
	while (m--)
	{
		k=gi();ans=sum=0;
		for (int i=1;i<=k;++i) t[i]=gi();
		sort(t+1,t+k+1,cmp_rank);k=unique(t+1,t+k+1)-t-1;
		for (int i=1,top=0;i<=k;++i)
		{
			(ans+=sum)%=mod;if (i==k) break;
			int val=lcp(t[i],t[i+1]),sz=1;
			while (top&&q[top]>val)
				sz+=w[top],sum-=1ll*(q[top]-val)*w[top],--top;
			q[++top]=val;w[top]=sz;sum+=val;
		}
		printf("%lld\n",ans);
	}
	return 0;
}
posted @ 2018-02-28 20:33  租酥雨  阅读(118)  评论(0编辑  收藏  举报