首页 > 专题系列 > Java解POJ > POJ 1451 T9 [解题报告] Java
2013
11-07

POJ 1451 T9 [解题报告] Java

T9

问题描述 :

Background

A while ago it was quite cumbersome to create a message for the Short Message Service (SMS) on a mobile phone. This was because you only have nine keys and the alphabet has more than nine letters, so most characters could only be entered by pressing one key several times. For example, if you wanted to type “hello” you had to press key 4 twice, key 3 twice, key 5 three times, again key 5 three times, and finally key 6 three times. This procedure is very tedious and keeps many people from using the Short Message Service.

This led manufacturers of mobile phones to try and find an easier way to enter text on a mobile phone. The solution they developed is called T9 text input. The “9″ in the name means that you can enter almost arbitrary words with just nine keys and without pressing them more than once per character. The idea of the solution is that you simply start typing the keys without repetition, and the software uses a built-in dictionary to look for the “most probable” word matching the input. For example, to enter “hello” you simply press keys 4, 3, 5, 5, and 6 once. Of course, this could also be the input for the word “gdjjm”, but since this is no sensible English word, it can safely be ignored. By ruling out all other “improbable” solutions and only taking proper English words into account, this method can speed up writing of short messages considerably. Of course, if the word is not in the dictionary (like a name) then it has to be typed in manually using key repetition again.



Figure 8: The Number-keys of a mobile phone.

More precisely, with every character typed, the phone will show the most probable combination of characters it has found up to that point. Let us assume that the phone knows about the words “idea” and “hello”, with “idea” occurring more often. Pressing the keys 4, 3, 5, 5, and 6, one after the other, the phone offers you “i”, “id”, then switches to “hel”, “hell”, and finally shows “hello”.

Problem

Write an implementation of the T9 text input which offers the most probable character combination after every keystroke. The probability of a character combination is defined to be the sum of the probabilities of all words in the dictionary that begin with this character combination. For example, if the dictionary contains three words “hell”, “hello”, and “hellfire”, the probability of the character combination “hell” is the sum of the probabilities of these words. If some combinations have the same probability, your program is to select the first one in alphabetic order. The user should also be able to type the beginning of words. For example, if the word “hello” is in the dictionary, the user can also enter the word “he” by pressing the keys 4 and 3 even if this word is not listed in the dictionary.

输入:

The first line contains the number of scenarios.

Each scenario begins with a line containing the number w of distinct words in the dictionary (0<=w<=1000). These words are iven in the next w lines in ascending alphabetic order. Every line starts with the word which is a sequence of lowercase letters from the alphabet without whitespace, followed by a space and an integer p, 1<=p<=100, representing the probability of that word. No word will contain more than 100 letters.

Following the dictionary, there is a line containing a single integer m. Next follow m lines, each consisting of a sequence of at most 100 decimal digits 2�, followed by a single 1 meaning “next word”.

输出:

The output for each scenario begins with a line containing “Scenario #i:”, where i is the number of the scenario starting at 1.

For every number sequence s of the scenario, print one line for every keystroke stored in s, except for the 1 at the end. In this line, print the most probable word prefix defined by the probabilities in the dictionary and the T9 selection rules explained above. Whenever none of the words in the dictionary match the given number sequence, print “MANUALLY” instead of a prefix.

Terminate the output for every number sequence with a blank line, and print an additional blank line at the end of every scenario.

样例输入:

2
5
hell 3
hello 4
idea 8
next 8
super 3
2
435561
43321
7
another 5
contest 6
follow 3
give 13
integer 6
new 14
program 4
5
77647261
6391
4681
26684371
77771

样例输出:

Scenario #1:
i
id
hel
hell
hello

i
id
ide
idea


Scenario #2:
p
pr
pro
prog
progr
progra
program

n
ne
new

g
in
int

c
co
con
cont
anoth
anothe
another

p
pr
MANUALLY
MANUALLY

解题代码:

//* @author: 
import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Scanner;

class node {
 char ch;// 字符
 int val;// 权值
 int lv;// 层次
 node father;// 父结点
 HashMap< Character, node> next;

node(char ch, int val, int lv, node father) {
 this.ch = ch;
 this.val = val;
 this.lv = lv;
 this.father = father;
 next = new HashMap< Character, node>();
}

node() {
 next = new HashMap< Character, node>();
 lv = 0;
}
}

class trie {
private static char t9[][] = { {}, {}, { 'a', 'b', 'c' }, { 'd', 'e', 'f' }, { 'g', 'h', 

'i' }, { 'j', 'k', 'l' }, { 'm', 'n', 'o' }, { 'p', 'q', 'r', 's' }, { 't', 'u', 'v' }, { 

'w', 'x', 'y', 'z' } };

node root = null;

public void add(String str, int val) {
  node curr = root;
  for (int i = 0; i < str.length(); i++) {
   char ch = str.charAt(i);
   // 没有结点就建立结点
    node next;
    if ((next = curr.next.get(ch)) == null) {
      curr.next.put(ch, new node(ch, val, curr.lv + 1, curr));
      curr = curr.next.get(ch);
    } else {
      curr = next;
      curr.val += val;
    }
  }
}

public void find(String num_str) {
  int length;
  int num[];
  // 找出1的位置,确定结束点
   int one_pos = num_str.indexOf('1');
   if (one_pos < 0) {
     length = num_str.length();
   } else {
     length = one_pos;
   }
// 字符转换为数字
num = new int[length];
for (int i = 0; i < length; i++) {
num[i] = num_str.charAt(i) - '0';
}
// 建立优先队列
PriorityQueue pq = new PriorityQueue(26, new Comparator() {
// 优先规则:层次从小到大,权值从大到小,字母表顺序
public int compare(node a, node b) {
if (a.lv == b.lv) {
if (a.val == b.val) {
return a.ch - b.ch;
} else {
return b.val - a.val;
}
} else {
return a.lv - b.lv;
}
}
});
// 把根加入队列
pq.add(root);
// 对trie树进行BFS遍历
int lv = 0;
while (pq.size() > 0) {
// 把所有可能接下来的结点列出,加入队列
node curr = pq.poll();
// 反推结果
if (curr.lv > lv) {
char res[] = new char[curr.lv];
node c = curr;
while (c != root) {
res[c.lv - 1] = c.ch;
c = c.father;
}
System.out.println(res);
lv++;
}
if (lv < num.length) {
int dig = num[curr.lv];
for (int i = 0; i < t9[dig].length; i++) {
node next;
if ((next = curr.next.get(t9[dig][i])) != null) {
pq.add(next);
}
}
}
}
// 填空
for (int i = lv; i < length; i++) {
System.out.println("MANUALLY");
}
}

trie() {
root = new node();
}
}

public class Main {
public static void main(String[] args) throws Exception {
Scanner cin = new Scanner(System.in);
int cas = cin.nextInt();
for (int th = 1; th <= cas; th++) {
System.out.printf("Scenario #%d:\n", th);
// 对每一个测试用例建立一棵trie树
trie tr = new trie();
int w = cin.nextInt();
while (w-- > 0) {
tr.add(cin.next(), cin.nextInt());
}
int m = cin.nextInt();
while (m-- > 0) {
String src = cin.next();
tr.find(src);
System.out.println();
}
System.out.println();
}
}
}

  1. 代码是给出了,但是解析的也太不清晰了吧!如 13 abejkcfghid jkebfghicda
    第一步拆分为 三部分 (bejk, cfghi, d) * C(13,3),为什么要这样拆分,原则是什么?