hihocoder 1066 并查集java实现

public   class  Week14 {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int index = Integer.parseInt(scanner.nextLine());

HashMap<String, String> map = new HashMap<String, String>();

for(int i=0; i<indexi++){

String temp = scanner.nextLine();

int mark = Integer.parseInt(temp.split(" ")[0]);

String people1 = temp.split(" ")[1];

String people2 = temp.split(" ")[2];

if(mark == 0) Week14.insert(people1people2map);

if(mark == 1){

//如果想这样检查的话,要返回null的字符串,而不是null !!!!!!

// if(!Week14.find(people1, map).equals("null") && !Week14.find(people2, map).equals("null")){

// while( !people1.equals(Week14.find(people1, map)) ){

// people1 = Week14.find(people1, map);

// }

// while( !people2.equals(Week14.find(people2, map)) ){

// people2 = Week14.find(people2, map);

// }

// if(people1.equals(people2)) System.out.println("yes");

// else System.out.println("no");

// }

// else{

// System.out.println("no");

// }

if(!map.containsKey(people1) || !map.containsKey(people2)){

System.out.println("no");

}

else{

while( !people1.equals(Week14.find(people1map)) ){

people1 = Week14.find(people1map);

}

while( !people2.equals(Week14.find(people2map)) ){

people2 = Week14.find(people2map);

}

if(people1.equals(people2)) System.out.println("yes");

else System.out.println("no");

}

}

}

}

public static void insert(String people1, String people2, HashMap<String, String> map){

if(map.containsKey(people1)){

if(map.containsKey(people2)){

if(map.get(people1).equals(people2)) ; //相同情况,换顺序

else{

while( !people1.equals(Week14.find(people1map)) ){

people1 = Week14.find(people1map);

}

while( !people2.equals(Week14.find(people2map)) ){

people2 = Week14.find(people2map);

}

map.replace(people2people1);

}

}

else map.put(people2people1); //后指前

else{

if(map.containsKey(people2)) map.put(people1people2); //前指后

else{

map.put(people1people1); //设置前面为终点

map.put(people2people1); //后指前

}

}

}

public static String find(String people1, HashMap<String, String> map){

if(map.containsKey(people1)) return map.get(people1);

else return "null";

}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值