poj2001(Trie树)

点击打开题目链接


大致题意:给定一系列单词,为每个单词寻找最短前缀使其能被唯一标识,与其他单词都区分开来

网上百度出的几道Trie树的题目发现用容器,比如HashMap等就可以做,但是这道似乎就不行了,相当来说

应该是Trie树的典型应用题。思路比较简单,就是Trie树建立,结点统计被几个单词占用了,然后再对每个单词

遍历一遍Trie树找到第一个结点只被该单词占用的(即该结点上记录的cnt值为1)。如果遍历完了都没有,说明

该单词最短前缀只能是该单词自身了。其实理解了Trie树这道题还是好做的。


代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	/**
	 * @param args
	 */
	static BufferedReader reader;
	static String str;
	static char ch[][];
	static int cnt, num;
	static int arr[][];
	static int word[], nums[], pre[], ans[];

	private static void deal() {
		int number, totalnum;
		totalnum = 0;
		word = new int[21 * cnt + 1];
		nums = new int[21 * cnt + 1];
		ans = new int[cnt + 1];
		for (int i = 1; i <= cnt; i++) {
			number = 0;
			for (int j = 0; j < ch[i].length; j++)
				if (arr[number][ch[i][j] - 'a'] == 0) {
					totalnum++;
					arr[number][ch[i][j] - 'a'] = totalnum;
					nums[totalnum]++;
					number = totalnum;
				} else {
					number = arr[number][ch[i][j] - 'a'];
					nums[number]++;
				}
			word[number] = i;
		}
		for (int i = 1; i <= cnt; i++) {
			number = 0;
			totalnum = 0;
			for (int j = 0; j < ch[i].length; j++) {
				number = arr[number][ch[i][j] - 'a'];
				totalnum++;
				if (nums[number] == 1)
					break;
			}
			ans[i] = totalnum;
		}
		for (int i = 1; i <= cnt; i++) {
			for (int j = 0; j < ch[i].length; j++)
				System.out.print(ch[i][j]);
			System.out.print(" ");
			for (int j = 0; j < ans[i]; j++)
				System.out.print(ch[i][j]);
			System.out.println();
		}
	}

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		reader = new BufferedReader(new InputStreamReader(System.in));
		str = reader.readLine();
		ch = new char[1001][];
		cnt = 0;
		while (str != null) {
			cnt++;
			ch[cnt] = str.toCharArray();
			str = reader.readLine();
		}
		arr = new int[21 * cnt + 1][27];
		deal();
	}

}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/lixiaomu2/article/details/71756406
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞