Uva 10282

/*
 * 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]);
				}
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值