HDU4416 Good Article Good sentence 題解&代碼

啦啦啦,第三道強行算作今天(19號)完成,flag get,開心
這道看到它各種RE心都碎了…於是查出了兩個錯
1、關於字符串rank最後補0,我栽在了多組數據上…平時單組我就強行當做自己補過0了,結果吃了個虧,折騰了半個小時才發現
2、關於分隔字符也是人…23333333我開了2w+的數組RE了,交了好幾遍改了好幾次都沒發現,最後看題解發現人家開了3w

最近好像懶了很多,題解越來越短啦…不過今天太困了【強行辯解

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define LL long long
using namespace std;
const int maxn=300005;
const int maxm=maxn;
char str[maxn];
LL ans;
int T,t,n,m,len,l,tot,temp,pos[maxn];
int num[maxn],sa[maxn],rk[maxn],height[maxn];
int wa[maxn],wb[maxn],wv[maxn],cnt[maxm];
void DA(int *r,int n,int m)
{
    int *x=wa,*y=wb,p;
    for(int i=0;i<m;i++)cnt[i]=0;
    for(int i=0;i<n;i++)cnt[x[i]=r[i]]++;
    for(int i=1;i<m;i++)cnt[i]+=cnt[i-1];
    for(int i=n-1;i>=0;i--)sa[--cnt[x[i]]]=i;
    for(int j=1;j<n;j<<=1)
    {
        p=0;
        for(int i=n-j;i<n;i++)y[p++]=i;
        for(int i=0;i<n;i++)if(sa[i]-j>=0)y[p++]=sa[i]-j;
        for(int i=0;i<n;i++)wv[i]=x[y[i]];
        for(int i=0;i<m;i++)cnt[i]=0;
        for(int i=0;i<n;i++)cnt[wv[i]]++;
        for(int i=1;i<m;i++)cnt[i]+=cnt[i-1];
        for(int i=n-1;i>=0;i--)sa[--cnt[wv[i]]]=y[i];
        swap(x,y);
        p=1;x[sa[0]]=0;
        for(int i=1;i<n;i++)
            x[sa[i]]=(y[sa[i]]==y[sa[i-1]] && y[sa[i]+j]==y[sa[i-1]+j])?p-1:p++;
        if(p>=n)break;
        m=p;
    }
    for(int i=1;i<n;i++)rk[sa[i]]=i;
}
void calheight(int *r,int n)
{
    int j=0,k=0;
    for(int i=0;i<n;height[rk[i]]=k,i++)
        for(k?k--:k=0,j=sa[rk[i]-1];r[i+k]==r[j+k];k++);
}
int main(void)
{
    scanf("%d",&T);
    while(T--)
    {
        m=0,tot=27;
        scanf("%d",&n);
        scanf("%s",str);
        len=strlen(str);
        for(int i=0;i<len;i++)num[m++]=str[i]-'a'+1;
        for(int i=0;i<n;i++)
        {
            num[m++]=tot++;
            scanf("%s",str);
            l=strlen(str);
            for(int j=0;j<l;j++)
                num[m++]=str[j]-'a'+1;
        }
        num[m]=0;
        DA(num,m+1,tot+1);
        calheight(num,m);
        memset(pos,0,sizeof(pos));
        temp=maxn;
        for(int i=1;i<=m;i++)
            if(sa[i]<len)
            {
                if(height[i]<temp) temp=height[i];
                if(pos[sa[i]]<temp) pos[sa[i]]=temp;
            }
            else temp=maxn;
        temp=maxn;
        for(int i=m;i>=1;i--)
            if(sa[i-1]<len)
            {
                if(height[i]<temp) temp=height[i];
                if(pos[sa[i-1]]<temp) pos[sa[i-1]]=temp;
            }
            else temp=maxn;
        for(int i=1;i<=m;i++)
             if(sa[i]<len&& sa[i-1]<len)
                if(pos[sa[i-1]]<height[i])
                    pos[sa[i-1]]=height[i];
        ans=(LL)len*(LL)(len+1)/(LL)2;
        for(int i=0;i<len;i++)ans-=pos[i];
        cout<<"Case "<<++t<<": "<<ans<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章