POJ 2001 Shortest Prefixes

一个比较差不多点很水的字典树,并不难。。细节没有处理好WA了N次之后终于发现了

测试输入数据:

ababa

abab

aa

a

正确输出

ababa ababa

abab abab

aa aa

a

代码注释部分是我错的地方。。想太多了

#include<stdio.h>
#include<string.h>
#include<iostream>
struct node
{
    int size;
    node *ch[26];
    node()
    {
        size = 0;
        for(int i = 0 ; i < 26 ; i++)
        {
            ch[i] = NULL;
        }
    }
};
node *root = new node;
node *current,*newnode;
void INSERT(char *s)
{
    int len = strlen(s);
    int i,m;
    current = root;
    for(i = 0 ; i < len ;i++)
    {
        m = s[i]-'a';
        if(current->ch[m]!=NULL)
        {
            current = current->ch[m];
            (current->size)++;
        }
        else
        {
            newnode = new node;
            (newnode->size)++;
            current->ch[m] = newnode;
            current = newnode;
        }
    }
}
void QUERY(char *s)
{
    int i,m;
    current = root;
    for(i = 0 ; i < strlen(s);i++)
    {
        m = s[i]-'a';
        if(strlen(s)==1)
        {
            printf("%c",s[i]);
            return ;
        }
        current = current->ch[m];
        if((current->size)>1)
            printf("%c",s[i]);
        else if(current->size==1)
            {
//                if(i!=strlen(s)-1)
                    printf("%c",s[i]);
                return ;
            }
    }
}
char s[10005][22];
using namespace std;
int main()
{
    int N;
    N = 0;
    while(gets(s[N]))
    {
        INSERT(s[N]);
        N++;
    }
    for(int i = 0 ; i < N; i++)
    {
        printf("%s ",s[i]);
        QUERY(s[i]);
        printf("\n");
    }
    return 0;
}


你可能感兴趣的:(POJ 2001 Shortest Prefixes)