`

poj 2001

 
阅读更多

题意:给出n个单词(1<=n<=1000),求出每个单词的非公共前缀,如果没有,则输出自己。

 

思路:基础的trie。

 

只要基本了解Trie的构造与查找过程,就可以去做了。

代码如下所示:

#include<iostream>
using namespace std;
const int Max = 1002;
const int branchNum = 26;

struct tree_node
{
    int count;   // 记录用到这个节点的单词数量,如果=1,则证明其为这个单词唯一的节点。
    tree_node *next[branchNum];
}root,node[20*Max];
int p = 0;      //  静态建树的特点,记录用了几个tree_node,则下一个节点为node[p]。

void insert(char *word)
{
    tree_node *location = &root; //  起初先指向根,再一层层向下查找。
    while(*word)
	{
        if(location->next[*word-'a'] == NULL)
		{
            node[p].count = 0;//  初始化新节点
            location->next[*word-'a'] = &node[p ++];
        }
        location = location->next[*word-'a'];
        location->count ++;
        word ++;
    }
}

void search(char *word)
{
    tree_node *location = &root;
    while(*word && location)
	{
        if(location->count == 1) 
			break;
        printf("%c", *word);
        location = location->next[*word-'a'];
        word ++;
    }
    printf("\n");
}

int main()
{
    char word[Max][21];
    int i, k = 0;
    while(scanf("%s", word[k])!= EOF)
	{
        insert(word[k]);
		k ++;
    }
    for(i = 0; i < k; i ++)
	{
        printf("%s ", word[i]);
        search(word[i]);
    }
    return 0;
}


 

分享到:
评论

相关推荐

    Trie树题解1

    在题目描述中提到的POJ1056、POJ1204、POJ2001、POJ2418、POJ2503、POJ2513和POJ1816等题目中,Trie树都起到了关键作用。 1. POJ1056 - 该题要求判断给定的二进制序列集合是否合法,即没有一个序列是另一个序列的...

    poj上算法题目分类

    - 1423, 1694, 1723, 1727, 1763, 1788, 1828, 1838, 1840, 2201, 2376, 2377, 2380, 1318, 1877, 1928, 1971, 1974, 1990, 2001, 2002, 2092, 2379, 1002, 1007, 2159, 2231, 2371, 2388 **关键知识点:** - **...

    poj 1003 Hangover

    Hangover Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 44187 Accepted: 20574 Description How far can you make a stack of cards overhang a table?...Mid-Central USA 2001

    poj pku 解题报告

    1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1011 1012 1013 1014 ...2001 2002 2018 2019 2021 2027 2033 2044 2051 2081 2084 2104 2109 2112 2135 2136 2137 2153 2155 2181 2182 2184 2185 2186 2187 2188 ...

    poj 1004 Financial Management

    Financial Management Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 49263 Accepted: 23921 Description Larry graduated this year and finally has a job....Mid-Atlantic 2001

    poj 1005 I Think I Need a Houseboat

    I Think I Need a Houseboat Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 41126 Accepted: 16537 Description Fred Mapper is considering purchasing some land in ...Mid-Atlantic 2001

    剪绳子leetcode-Online-Judge-Solutions:日常在线判断解决方案

    POJ : 内容 日期 ID 名称 类别 注释 18/09/17 OJ184 食物链 联合查找 NOI 2001 18/09/17 OJ1494 虫虫特工队 联合查找 18/10/12 LC307 范围总和查询 - 可变 二叉索引树 18/10/13 OJ197 手机 二叉索引树 IOI 2001 18/...

    北京大学acm题库 题目分类

    北京大学ACM题库分类是适合想做ACM题的人的题目分类,分类详细,涵盖了POJ(PKU ACM Online Judge)上的题目分类。该分类涵盖了多种算法和数据结构,包括排序、搜索、回溯、遍历、历法、枚举、数据结构的典型算法、...

Global site tag (gtag.js) - Google Analytics