[洛谷P2580]于是他错误的点名开始了(Trie树)

传送门

洛谷P2580的一个水题,用啥都能过,不过为了练习一下刚刚学会的字典树,还是认真做一下吧。

#include <cstdio>
#include <cstring>

using namespace std;

#define idx(x) x - 'a'

int n, m, nex;
struct node
{
    int next[26];
    int val;
}tree[1000001];

void Insert(char *s)
{
    int i, rt = 0, len = strlen(s) - 1;
    for(i = 0; i <= len; i++)
    {
        int c = idx(s[i]);
        if(!tree[rt].next[c]) tree[rt].next[c] = ++nex;
        rt = tree[rt].next[c];
    }
    tree[rt].val = 1;
}

int Find(char *s)
{
    int i, rt = 0, len = strlen(s) - 1;
    for(i = 0; i <= len; i++)
    {
        int c = idx(s[i]);
        if(!tree[rt].next[c]) return 0;
        rt = tree[rt].next[c];
    }
    if(tree[rt].val == 1)
    {
        tree[rt].val++;
        return 1;
    }
    else return 2;
}

int main()
{
    int i;
    char str[1000001];
    scanf("%d", &n);
    for(i = 1; i <= n; i++)
    {
        scanf("%s", str);
        Insert(str);
    }
    scanf("%d", &m);
    for(i = 1; i <= m; i++)
    {
        scanf("%s", str);
        int f = Find(str);
        if(f == 0) printf("WRONG\n");
        else if(f == 1) printf("OK\n");
        else printf("REPEAT\n");
    }
    return 0;
}
View Code

 

posted @ 2017-03-29 20:05  zht467  阅读(144)  评论(1编辑  收藏  举报