HDU 4436 str2int

2 篇文章 0 订阅
1 篇文章 0 订阅

http://acm.hdu.edu.cn/showproblem.php?pid=4436

思路:
标准的后缀自动机+拓扑排序题目。
首先建立后缀自动机,每次把10这个数作为分割点,对了,每个状态节点添加2个标识,一个cnt表示这个状态的出现次数,一个sum表示出现这个状态后所得到的和为多少。我们遍历所有状态,之后找出每个状态有那些儿子存在,之后我们更新儿子的cnt和sum,之后把所有状态的sum相加即可。

#include <bits/stdc++.h>
#define maxs 2002020
#define ll long long
#define mme(i,j) memset(i,j,sizeof(i))
using namespace std;
struct sam
{
    sam *pre,*son[12];
    int len,cnt,sum;
}*root,*tail,que[maxs],*b[maxs];
int tot;
char s[maxs];
void add(int c,int l)
{
    sam *p=tail,*np=&que[tot++];
    np->len=l;
    while(p&&p->son[c]==NULL){
        p->son[c]=np;
        p=p->pre;
    }
    if(p == NULL) np->pre = root;
    else {
        sam *q=p->son[c];
        if(p->len+1 == q->len) np->pre=q;
        else {
            sam *nq = &que[tot++];
            *nq = *q;
            nq->len = p->len+1;
            np->pre = q->pre =nq;
            while(p&&p->son[c]==q) p->son[c]=nq,p=p->pre;
        }
    }
    tail=np;
}
int c[maxs];
void topo(int len)
{
    mme(c,0);
    for(int i=0;i<tot;i++) c[que[i].len]++;
    for(int i=1;i<len;i++) c[i]+=c[i-1];
    for(int i=0;i<tot;i++) b[--c[que[i].len]] = &que[i];
    root->cnt=1;
    root->sum=0;
    int ans=0;
    for(int i=0;i<tot;i++){
        sam *now =b[i];
        for(int j=0;j<10;j++){
            if(i==0&&j==0) continue;
            if(now->son[j]){
                sam *nex = now->son[j];
                nex->cnt=(nex->cnt+now->cnt)%2012;
                nex->sum = (nex->sum+now->sum*10+now->cnt*j)%2012;
            }
        }
        ans=(ans+now->sum)%2012;
    }
    printf("%d\n",ans);
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        tot=0;
        root=tail=&que[tot++];
        int len=1;
        while(n--){
            scanf("%s",s);
            for(int i=0;s[i];i++) add(s[i]-'0',len++);
            add(10,len++);
        }
        topo(len);
        for(int i=0;i<tot;i++){
            que[i].cnt=que[i].sum=0;
            que[i].pre=NULL;
            mme(que[i].son,NULL);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值