spoj 694

http://www.elijahqi.win/2017/07/20/spoj-694/
Given a string, we need to find the total number of its distinct substrings.
Input
T- number of test cases. T<=20;
Each test case consists of one string, whose length is <= 1000
Output
For each test case output one number saying the number of distinct substrings.
Example
Sample Input:
2
CCCCC
ABABA
Sample Output:
5
9
Explanation for the testcase with string ABABA:
len=1 : A,B
len=2 : AB,BA
len=3 : ABA,BAB
len=4 : ABAB,BABA
len=5 : ABABA
Thus, total number of distinct substrings is 9.

题解:把所有子串全部相加,减去height即可

#include<cstdio>
#include<cstring>
#define N 55000 
char a[N];
int n,m,k,T,tmp[N],rank[N<<1],rank1[N],sa[N],height[N],count[N];
inline int max(int x,int y){
    return x>y?x:y;
}
int main(){
    freopen("spoj694.in","r",stdin);
    freopen("spoj694.out","w",stdout);
    scanf("%d",&T);
    while (T--){
        scanf("%s",a+1);n=strlen(a+1);m=0;
    //  for (int i=1;i<=n;++i) printf("%c ",a[i]);printf("\n");
        memset(count,0,sizeof (count));
        memset(rank,0,sizeof(rank));
        for (int i=1;i<=n;++i) count[a[i]]=1;
        for (int i=1;i<=255;++i) count[i]+=count[i-1],m=max(m,count[i]);
        for (int i=1;i<=n;++i) rank[i]=count[a[i]];
        k=0;
        for (int p=1;k!=n;p<<=1,m=k){
            for (int i=1;i<=m;++i) count[i]=0;
            for (int i=1;i<=n;++i) count[rank[i+p]]++;
            for (int i=1;i<=m;++i) count[i]+=count[i-1];
            for (int i=n;i>=1;--i) tmp[count[rank[i+p]]--]=i;
            for (int i=1;i<=m;++i) count[i]=0;
            for (int i=1;i<=n;++i) count[rank[i]]++;
            for (int i=1;i<=m;++i) count[i]+=count[i-1];
            for (int i=n;i>=1;--i) sa[count[rank[tmp[i]]]--]=tmp[i];
            memcpy(rank1,rank,sizeof(rank)>>1);
            rank[sa[1]]=k=1;
            for (int i=2;i<=n;++i){
                if (rank1[sa[i]+p]!=rank1[sa[i-1]+p]||rank1[sa[i]]!=rank1[sa[i-1]])++k;
                rank[sa[i]]=k;
            }
        }
    //  for (int i=1;i<=n;++i) printf("%d ",rank[i]);printf("\n");
        k=0;
        for (int i=1;i<=n;++i){
            if (rank[i]==1) continue;
            k=k==0?0:k-1;
            while (a[i+k]==a[sa[rank[i]-1]+k]) ++k;
            height[rank[i]]=k;
        }
        //for (int i=1;i<=n;++i) printf("%d ",height[i]);printf("\n");
        int ans=0;
        for (int i=1;i<=n;++i) ans+=i;
        for (int i=1;i<=n;++i) ans-=height[i];
        printf("%d\n",ans);
    }   
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值