POJ 2001 Shortest Prefixes

Description

A prefix of a string is a substring starting at the beginning of the given string. The prefixes of "carbon" are: "c", "ca", "car", "carb", "carbo", and "carbon". Note that the empty string is not considered a prefix in this problem, but every non-empty string is considered to be a prefix of itself. In everyday language, we tend to abbreviate words by prefixes. For example, "carbohydrate" is commonly abbreviated by "carb". In this problem, given a set of words, you will find for each word the shortest prefix that uniquely identifies the word it represents. 

In the sample input below, "carbohydrate" can be abbreviated to "carboh", but it cannot be abbreviated to "carbo" (or anything shorter) because there are other words in the list that begin with "carbo". 

An exact match will override a prefix match. For example, the prefix "car" matches the given word "car" exactly. Therefore, it is understood without ambiguity that "car" is an abbreviation for "car" , not for "carriage" or any of the other words in the list that begins with "car". 

本题是找出唯一标识指定字符串的最短前缀,采用字典树存储组给出的字符串,提高查找效率。具体实现代码如下:

#include <iostream>
#include <string>
using namespace std;

const int MAX = 1002;
const int NUM = 26;
 
struct TrieNode
{
    	int count;   
    	struct TrieNode *branch[NUM];
	TrieNode()
	{
		count = 0;
		for(int i = 0; i < NUM; i++)
		{
			branch[i] = NULL;
		}
	}
};

void insert(TrieNode *&root, string word)
{
    	TrieNode *p = root;
	if(p == NULL)
	{
		p = new TrieNode();
		root = p;
	}
   	for(int i = 0; i < word.size(); i++)
	{
        	if(p->branch[word[i] - 'a'] == NULL)
		{
            		p->branch[word[i] - 'a'] = new TrieNode();
        	}
        	p = p->branch[word[i] - 'a'];
        	p->count++;
    	}
}
 
string prefix(TrieNode *root, string word)
{
	string str = "";
    	TrieNode *p = root;
	for(int i = 0; i < word.size(); i++)
	{
        	if(p->count == 1) 
			break;

		str += word[i];
        	p = p->branch[word[i] - 'a'];
    	}
	return str;
}
 
int main()
{
	TrieNode *root = NULL;
    	string words[MAX];
    	int i, k = 0;
    	while(cin >> words[k])
	{
        	insert(root, words[k]);
        	k++;
    	}
    	for(i = 0; i < k; i++)
	{
		cout << words[i] << " " << prefix(root, words[i]) << endl;
    	}
    	return 0;
}


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