您的位置:首页 > 其它

hdu 1116 Play on Words

2011-09-13 12:38 459 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1116

这个题目要运用到欧拉路得相关知识,并且也要并查集,题目说的是:给你n个单词,要你判断这些单词能不能首尾相连。

理解题目意思后,进行转化,输入字符串,提取首位字母作为下标来表示两节点的出现,以及相对应节点入度和出度的增加,

转化为并查集的应用即可。那么从可以想象一幅由首位字母节点构成的图,当且仅当图是一条欧拉回路或者欧拉通路的时候,

才能满足题目的要求,至于欧拉回路和欧拉通路的判定可以总结为如下:

1)所有的点联通

2)欧拉回路中所有点的入度和出度一样。

3)欧拉通路中起点的入度 - 出度 = 1,终点的 初度 - 入度 = 1, 其他的所有点入度 = 出度;

/*
2011-9-13
author:BearFly1990
*/
package acm.hdu.tests;

import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner;

public class HDU_1116 {
private static int N = 40;
private static int[] father = new int
;
private static boolean[] visited = new boolean
;
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
int[] sin = new int
;
int[] out = new int
;
int[] p = new int
;
int T;
T = in.nextInt();
while(T-- > 0){
int n = in.nextInt();
Arrays.fill(sin, 0);
Arrays.fill(out, 0);
Arrays.fill(p, 0);
Arrays.fill(visited, false);
for(int i=0; i<26; i++)
father[i]=i;
while(n-- > 0){
String str = in.next();
int a = str.charAt(0) - 'a';
int b = str.charAt(str.length() - 1) - 'a';
merge(a,b);
out[a]++;
sin[b]++;
visited[a] = true;
visited[b] = true;
}

for(int i = 0; i < 26; i++){
father[i] = find(i);
}

int count = 0;
for(int i = 0; i < 26; i++){
if(visited[i] && father[i] == i){
count ++;
}
}

if(count > 1){
System.out.printf("The door cannot be opened.\r\n");
continue;
}
int j  = 0 ;
for(int i = 0; i < 26 ; i++){
if(visited[i] && sin[i] != out[i]){
p[j++] = i;
}
}
if(j == 0){
System.out.printf("Ordering is possible.\r\n");
continue;
}
if(j==2 && ( out[p[0]]-sin[p[0]]==1 && sin[p[1]]-out[p[1]]==1
|| out[p[1]]-sin[p[1]]==1 && sin[p[0]]-out[p[0]]==1 ) ) {
System.out.printf("Ordering is possible.\r\n");
continue;
}

System.out.printf("The door cannot be opened.\r\n");

}
}
public static int find(int x){
if(father[x] != x){
father[x] = find(father[x]);
}
return father[x];
}
public static void merge(int a,int b){
int x,y;
x = find(a);
y = find(b);
if(x != y)father[x] = y;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: