poj2001 (Trie tree)

Click to open the question link


General meaning: Given a series of words, find the shortest prefix for each word so that it can be uniquely identified and distinguished from other words


Several Trie tree titles published by Baidu on the Internet found that containers, such as HashMap, can be used, but this one does not seem to work.

It should be a typical application problem of Trie tree. The idea is relatively simple, that is, the Trie tree is established, the node statistics are occupied by several words, and then each word is

Traverse the Trie tree to find the first node that is only occupied by the word (that is, the cnt value recorded on the node is 1). If there is none after traversing, explain

The shortest prefix of the word can only be the word itself. In fact, the problem of understanding the Trie tree is still easy to do.


code show as below:

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;
		total = 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;
			total = 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] = total;
		}
		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();
	}

}


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326742259&siteId=291194637