[USACO]Name That Number

Name That Number

Among the large Wisconsin cattle ranchers, it is customary to brand cows with serial numbers to please the Accounting Department. The cow hands don't appreciate the advantage of this filing system, though, and wish to call the members of their herd by a pleasing name rather than saying, "C'mon, #4734, get along."

Help the poor cowhands out by writing a program that will translate the brand serial number of a cow into possible names uniquely associated with that serial number. Since the cow hands all have cellular saddle phones these days, use the standard Touch-Tone(R) telephone keypad mapping to get from numbers to letters (except for "Q" and "Z"):

          2: A,B,C     5: J,K,L    8: T,U,V
          3: D,E,F     6: M,N,O    9: W,X,Y
          4: G,H,I     7: P,R,S

Acceptable names for cattle are provided to you in a file named "dict.txt", which contains a list of fewer than 5,000 acceptable cattle names (all letters capitalized). Take a cow's brand number and report which of all the possible words to which that number maps are in the given dictionary which is supplied as dict.txt in the grading environment (and is sorted into ascending order).

For instance, the brand number 4734 produces all the following names:

GPDG GPDH GPDI GPEG GPEH GPEI GPFG GPFH GPFI GRDG GRDH GRDI
GREG GREH GREI GRFG GRFH GRFI GSDG GSDH GSDI GSEG GSEH GSEI
GSFG GSFH GSFI HPDG HPDH HPDI HPEG HPEH HPEI HPFG HPFH HPFI
HRDG HRDH HRDI HREG HREH HREI HRFG HRFH HRFI HSDG HSDH HSDI
HSEG HSEH HSEI HSFG HSFH HSFI IPDG IPDH IPDI IPEG IPEH IPEI
IPFG IPFH IPFI IRDG IRDH IRDI IREG IREH IREI IRFG IRFH IRFI
ISDG ISDH ISDI ISEG ISEH ISEI ISFG ISFH ISFI

As it happens, the only one of these 81 names that is in the list of valid names is "GREG".

Write a program that is given the brand number of a cow and prints all the valid names that can be generated from that brand number or ``NONE'' if there are no valid names. Serial numbers can be as many as a dozen digits long.

PROGRAM NAME: namenum

INPUT FORMAT

A single line with a number from 1 through 12 digits in length.

SAMPLE INPUT (file namenum.in)

4734

OUTPUT FORMAT

A list of valid names that can be generated from the input, one per line, in ascending alphabetical order.

SAMPLE OUTPUT (file namenum.out)

GREG

思路:
首先是用什麼數據結構來保存字典;
然後就是用什麼算法去查找數字對應詞典中的單詞。

字典用26階樹來保存,查找則選用了回溯算法。

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//MAXIME 629463
public class namenum {
    								//2		//3		4		//5		//6		//7		//8		//9
    public static final char[][] keyboard = {{'A','B','C'},{'D','E','F'},{'G','H','I'},{'J','K','L'},{'M','N','O'},{'P','R','S'},{'T','U','V'},{'W','X','Y'}};
    public static void main(String args[]) throws FileNotFoundException,IOException {
	long start = System.currentTimeMillis();
	BufferedReader br = new BufferedReader(new FileReader("namenum.in"));
	FileWriter fout = new FileWriter("namenum.out");
	tree DT = new tree();
	pre_process(DT,"dict.txt");
	String phonenumber = br.readLine();
	StringBuffer sb = new StringBuffer();
	if(!getWord(phonenumber.toCharArray(),DT,0,sb,fout))
	    fout.write("NONE\n");
	fout.flush();
	fout.close();
	br.close();
	long end = System.currentTimeMillis();
	System.out.println(end-start);
	System.exit(0);
    }
    public static boolean getWord(char[] source,tree dict,int position,StringBuffer sb,FileWriter fout) throws IOException {
	boolean hasword=false;
	int number = source[position]-'0';
	if(number<2||number>9||dict==null) {
	    return false;
	}
	if(position==source.length-1) {
	    for(int i =0;i<3;i++) {
		if(dict.getChildren(keyboard[number-2][i])!=null&&dict.getChildren(keyboard[number-2][i]).isWord()) {
		    fout.write(sb.toString()+keyboard[number-2][i]+"\n");
		    hasword=true;
		}
	    }
	    return hasword;
	}
	tree tmp = dict.getChildren(keyboard[number-2][0]);
	
	hasword |= getWord(source,tmp,position+1,(new StringBuffer(sb)).append(keyboard[number-2][0]),fout);
	tmp = dict.getChildren(keyboard[number-2][1]);
	hasword |=getWord(source,tmp,position+1,(new StringBuffer(sb)).append(keyboard[number-2][1]),fout);
	tmp = dict.getChildren(keyboard[number-2][2]);
	hasword |=getWord(source,tmp,position+1,(new StringBuffer(sb)).append(keyboard[number-2][2]),fout);
	return hasword;
    }
    public static void pre_process(tree dict,String filepath) throws FileNotFoundException,IOException {
	BufferedReader br = new BufferedReader(new FileReader(filepath));
	String word = br.readLine();
	tree tmp = null;
	while(word!=null) {
	    tmp = dict;
	    insert(tmp,word);
	    word = br.readLine();
	}
    }
    private static void insert(tree t,String word) {
	if(word==null||word.length()==0) {
	    return;
	}
	char[] tmp = word.toCharArray();
	for(int i = 0;i<tmp.length;i++) {
	    if(t.getChildren(tmp[i])==null) {
		t.setChildren(tmp[i]);
	    }
	    t = t.getChildren(tmp[i]);
	    
	}
	t.wordend();
    }
}
class tree{
    private boolean status = false;
    private tree[] children;
    public tree() {
	this.status=false;
	this.children = new tree[26];
    }
    public boolean isWord() {
	return this.status;
    }
    public void wordend() {
	this.status = true;
    }
    public tree getChildren(char c) {
	if(c<'A'||c>'Z') {
	    return null;
	}
	return children[c-'A'];
    }
    public void setChildren(char c) {
	children[c-'A'] = new tree();
    }
}

沒注意到一個細節:辭典是有序的。

定勢了,總想着將辭典全部保存到內存中已減少IO,如果能夠做到online查找,就沒有必要將全部信息一次都加載至內存。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章