【后缀自动机】 HDOJ 4436 str2int

一眼后缀数组。但是本弱不会写。本弱参考cxlove大神的。。。http://blog.csdn.net/ACM_cxlove?viewmode=contents

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 200005
#define maxm 100005
#define eps 1e-10
#define mod 2012
#define INF 1e9
#define lowbit(x) (x&(-x))  
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid  
#define rson o<<1 | 1, mid+1, R  
typedef long long LL;
//typedef int LL;
using namespace std;

struct node
{
	int step, cnt, sum;
	node *ch[11], *fa;
}pool[maxn], *root, *tail, *b[maxn];
int tot, n, cc[maxn], lengh;
char s[maxn];
node* newnode(void)
{
	node *top = &pool[tot++];
	top->sum = top->cnt = top->step = 0;
	for(int i = 0; i < 11; i++) top->ch[i] = NULL;
	top->fa = NULL;
	return top;
}
void add(int c, int len)
{
	node *np = newnode(), *p = tail;
	np->step = len, tail = np;
	for(; p && !p->ch[c]; p = p->fa) p->ch[c] = np;
	if(!p) np->fa = root;
	else if(p->ch[c]->step == p->step + 1) np->fa = p->ch[c];
	else {
		node *q = p->ch[c], *tmp = newnode();
		*tmp = *q;
		tmp->step = p->step + 1;
		np->fa = q->fa = tmp;
		for(; p && p->ch[c] == q; p = p->fa) p->ch[c] = tmp;
	}
}
void init(void)
{
	tot = 0;
	root = tail = newnode();
	root->cnt = 1;
}
void read(void)
{
	int len;
	lengh = 1;
	for(int i = 1; i <= n; i++) {
		scanf("%s", s);
		len = strlen(s);
		for(int j = 0; j < len; j++)
			add(s[j] - '0', lengh++);
		add(10, lengh++);
	}
}
void work(void)
{
	int ans = 0;
	memset(cc, 0, sizeof cc);
	for(int i = 0; i < tot; i++) cc[pool[i].step]++;
	for(int i = 1; i < lengh; i++) cc[i] += cc[i-1];
	for(int i = 0; i < tot; i++) b[--cc[pool[i].step]] = &pool[i];
	for(int i = 0; i < tot; i++) {
		node *p = b[i];
		for(int j = 0; j < 10; j++) {
			if(i == 0 && j == 0) continue;
			if(p->ch[j]) {
				node *q = p->ch[j];
				q->cnt = (q->cnt + p->cnt) % mod;
				q->sum = (q->sum + p->sum * 10 + p->cnt*j) % mod;
			}
		}
		ans = (ans + p->sum) % mod;
	}
	printf("%d\n", ans);
}
int main(void)
{
	while(scanf("%d", &n)!=EOF) {
		init();
		read();
		work();
	}
	return 0;
}


你可能感兴趣的:(HDU)