/*
* UVa 10282 字典
* */
//import java.io.BufferedInputStream;
//import java.io.FileInputStream;
import java.util.Scanner;
class Main {
static final int SEED = 131;// 31,131,1313,13131,131313...
static final int MAX = 1000003;// hash表长度
static final int MAXSTATE = 100010;// 字典最多条目数
int[] head = new int[MAX];
int[] next = new int[MAXSTATE];
String[] dicdia = new String[MAXSTATE]; // 存储方言
String[] diceng = new String[MAXSTATE]; // 存储英文单词
private int BKDR_HASH(String s) {
char[] chars = s.toCharArray();
int hash = 0;
for (int i = 0; i < chars.length; i++) {
hash = hash * SEED + chars[i];
}
return Math.abs(hash % MAX);
}
private int isFound(String s) {
int h = BKDR_HASH(s);
int u = head[h];// 从表头开始查找
while (u > 0) {
if (dicdia[u].equals(s)) {// 找到返回u
return u;
}
u = next[u];
}
return -1;
}
private boolean try_to_insert(int s) {
int h = BKDR_HASH(dicdia[s]);
int u = head[h];// 从表头开始查找
while (u > 0) {
if (dicdia[u].equals(dicdia[s]))// 如果已经存在插入失败
return false;
u = next[u];
}
next[s] = head[h];// 插入到链表中
head[h] = s;
return true;
}
public static void main(String[] args) throws Exception {
Main d = new Main();
// 输入重定向
/*BufferedInputStream in = new BufferedInputStream(new FileInputStream("dic.txt"));
System.setIn(in);*/
Scanner scanner = new Scanner(System.in);
int position = 1;
while (scanner.hasNext()) {
String s = scanner.nextLine();
if (s.length() > 0 && s.contains(" ")) {
String[] ss = s.split(" ");
d.dicdia[position] = ss[1];
d.diceng[position] = ss[0];
d.try_to_insert(position++);
} else if (s.length() > 0 && !s.contains(" ")) {
int pos = d.isFound(s);
if (pos == -1) {
System.out.println("eh");
} else {
System.out.println(d.diceng[pos]);
}
}
}
}
}
Uva 10282
最新推荐文章于 2017-10-21 17:48:04 发布