# [BZOJ4199][NOI2015]品酒大会（后缀数组+单调栈+ST表）

## 代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#define Pow 19
using namespace std;
const long long inf=2e18;
int n,len,a[300010],top,st[300010],cnt[300010],m,p,b[300010],SA[300010],rank[300010],L[300010],now;
int height[300010],*x,*y,Xx[300010],Yy[300010];
char s[300010];
long long f[300010],Maxp[300010],Minn[300010],Max[300010];
namespace STtable{
int Max[300010][22],Min[300010][22],lg[300010];
void build(){
for (int i=1,p=0;i<=n;i++){
while ((1<<p)<=i) ++p;
lg[i]=p-1;
}
for (int i=0;i<n;i++)
Min[i][0]=Max[i][0]=a[SA[i]];
for (int i=1;i<=Pow;i++)
for (int j=0;j<n;j++){
int pos=j+(1<<(i-1));
if (pos>=n) break;
Min[j][i]=min(Min[j][i-1],Min[pos][i-1]);
Max[j][i]=max(Max[j][i-1],Max[pos][i-1]);
}
}
long long getMax(int l,int r){
int j=lg[r-l+1];
return max(Max[l][j],Max[r-(1<<j)+1][j]);
}
long long getMin(int l,int r){
int j=lg[r-l+1];
return min(Min[l][j],Min[r-(1<<j)+1][j]);
}
}
bool cmp(int i,int j,int l){
return y[i]==y[j]&&((i+l>=len)?-1:y[i+l])==((j+l>=len)?-1:y[j+l]);
}
void get_SA(){
m=200;x=Xx;y=Yy;
for (int i=0;i<len;i++) ++b[x[i]=s[i]];
for (int i=1;i<=m;i++) b[i]+=b[i-1];
for (int i=len-1;i>=0;i--) SA[--b[x[i]]]=i;
for (int k=1;k<=len;k<<=1){
p=0;
for (int i=len-k;i<len;i++) y[p++]=i;
for (int i=0;i<len;i++)
if (SA[i]>=k) y[p++]=SA[i]-k;
for (int i=0;i<=m;i++) b[i]=0;
for (int i=0;i<len;i++) ++b[x[y[i]]];
for (int i=1;i<=m;i++) b[i]+=b[i-1];
for (int i=len-1;i>=0;i--) SA[--b[x[y[i]]]]=y[i];
swap(x,y);p=1;x[SA[0]]=0;
for (int i=1;i<len;i++)
x[SA[i]]=cmp(SA[i-1],SA[i],k)?p-1:p++;
if (p>len) break;m=p;
}
p=0;
for (int i=0;i<len;i++) rank[SA[i]]=i;
for (int i=0;i<len;i++){
if (rank[i]==0) continue;
int j=SA[rank[i]-1];
while (i+p<len&&j+p<len&&s[i+p]==s[j+p]) ++p;
height[rank[i]]=p;
if (p!=0) p--;
}
}
Minn[i]=min(Minn[i],val);
Maxp[i]=max(Maxp[i],val);
}
void calc(int i){
int len=i-L[i],c=now-cnt[i];
long long Maxnow,Minnow;
f[height[i]]+=(long long)len*c;
Maxnow=STtable::getMax(cnt[i]+1,now);
Minnow=STtable::getMin(cnt[i]+1,now);
Max[height[i]]=max(Max[height[i]],Maxnow*Maxp[i]);
Max[height[i]]=max(Max[height[i]],Minnow*Minn[i]);
}
int main()
{
scanf("%d",&n);
for (int i=0;i<n;i++){
char c=getchar();
while (c<'a'||c>'z') c=getchar();
s[i]=c;
}
for (int i=0;i<n;i++) scanf("%d",&a[i]);
len=n;get_SA();
STtable::build();
for (int i=0;i<=n;i++) Max[i]=Maxp[i]=-inf;
for (int i=0;i<=n;i++) Minn[i]=inf;
for (int i=1;i<len;i++){
L[i]=i-1;
while (top!=0&&height[st[top]]>=height[i]){
calc(st[top]);L[i]=L[st[top]];
--top;
}
st[++top]=i;cnt[i]=now;++now;
}
while (top!=0){calc(st[top]);--top;}
for (int i=len-1;i>=0;i--){
Max[i]=max(Max[i],Max[i+1]);
f[i]=f[i]+f[i+1];
}
for (int i=0;i<len;i++)
if (Max[i]==-inf) Max[i]=0;
for (int i=0;i<len;i++)
printf("%I64d %I64d\n",f[i],Max[i]);
return 0;
}


• 评论

• 上一篇
• 下一篇