POJ 2503 - Babelfish(字典树)

题目:

http://poj.org/problem?id=2503

思路:

字典树模板~~

AC.

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int M = 260050;
char word[100005][15];
int wp;
struct node {
    int next[26], value;
    bool ed;
}tree[M];
int pi;

void init()
{
    memset(tree, 0, sizeof(tree));
    pi = 1;
    wp = 0;
}
void inser(char *keyword, int value)
{
    int index, p = 0;
    for(int i = 0; keyword[i]; ++i) {
        index = keyword[i] - 'a';
        if(tree[p].next[index] == 0) {
            tree[p].next[index] = pi++;
        }
        p = tree[p].next[index];
//printf("%d ", p);
    }
    //printf("\n");
    tree[p].value = value;
    tree[p].ed = 1;
}
bool query(char *keyword, int &value)
{
    int index, p = 0;
    for(int i = 0; keyword[i]; ++i) {
        index = keyword[i] - 'a';
        if(tree[p].next[index] == 0) return 0;
        p = tree[p].next[index];
    }
    if(tree[p].ed) {
        value = tree[p].value;
        return 1;
     }
     return 0;
}
int main()
{
    //freopen("in", "r", stdin);
    init();
    char s1[15], s2[15], s[30];
    int value;
    while(gets(s)) {
        if(!strlen(s)) break;
        int i;
        int len = strlen(s);
        for(i = 0; i < len; ++i) {
            if(s[i] == ' ') break;
        }
        strncpy(s1, s, i);
        s1[i] = 0;
        strcpy(s2, s+i+1);
        strcpy(word[wp], s1);
        inser(s2, wp++);
    }
    while(~scanf("%s", s)) {
        if(query(s, value)) {
            printf("%s\n", word[value]);
        }
        else printf("eh\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值