URAL 2040 Palindromes and Super Abilities 2(回文树)

Time Limit: 1MS Memory Limit: 102400KB 64bit IO Format: %I64d & %I64u

Status

Description

Dima adds letters  s 1, …,  s n one by one to the end of a word. After each letter, he asks Misha to tell him how many new palindrome substrings appeared when he added that letter. Two substrings are considered distinct if they are different as strings. Which  nnumbers will be said by Misha if it is known that he is never wrong?

Input

The input contains a string  s 1 …  s n consisting of letters ‘a’ and ‘b’ (1 ≤  n ≤ 5 000 000).

Output

Print  n numbers without spaces:  i-th number must be the number of palindrome substrings of the prefix  s 1 …  s i minus the number of palindrome substrings of the prefix s 1 …  s i−1. The first number in the output should be one.

Sample Input

input output
abbbba
111111

Notes

We guarantee that jury has C++ solution which fits Time Limit at least two times. We do not guarantee that solution on other languages exists (even Java).

Source

Problem Author: Mikhail Rubinchik (prepared by Kirill Borozdin) 
Problem Source: Ural FU Dandelion contest. Petrozavodsk training camp. Summer 2014 

每插入一个字符都会有两种情况,产生新的回文树节点,不产生新的节点。所以答案只会是0,1
#include <iostream>
#include <string.h>

#include <stdlib.h>
#include <math.h>
#include <stdio.h>

using namespace std;
typedef long long int LL;
const int MAX=5*1e6;
const int maxn=4*1e6+5;
char str[MAX+5];
struct Tree
{
    int next[maxn][2];
    int fail[MAX+5];
    int len[MAX+5];
    int s[MAX+5];
    int last,n,p;
    int new_node(int x)
    {
        memset(next[p],0,sizeof(next[p]));
        len[p]=x;
        return p++;
    }
    void init()
    {
        p=0;
        new_node(0);
        new_node(-1);
        last=0;n=0;
        s[0]=-1;
        fail[0]=1;
	}
    int get_fail(int x)
    {
        while(s[n-len[x]-1]!=s[n])
            x=fail[x];
        return x;
    }
    int add(int x)
    {
        x-='a';
        s[++n]=x;
        int cur=get_fail(last);
        if(!(last=next[cur][x]))
        {
            int now=new_node(len[cur]+2);
            fail[now]=next[get_fail(fail[cur])][x];
            next[cur][x]=now;
            last=now;
            return 1;
        }
        return 0;
    }

}tree;
char ans[MAX+5];
int main()
{
    while(scanf("%s",str)!=EOF)
    {
       
        tree.init();
		int i;
        for( i=0;str[i];i++)
        {
			if(!tree.add(str[i]))
			    ans[i]='0';
			else
				ans[i]='1';
		}
		ans[i]='\0';
		puts(ans);
	}
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值