您的位置:首页 > Web前端

POJ 2492 A Bug's Life

2017-05-14 11:42 155 查看
题目链接:http://poj.org/problem?id=2492

题目大意:给出n种昆虫,并给出这些昆虫中配对的情况,让你判断有没有同性恋的虫子。

题目理解:每种昆虫之间都有必然的关系——同性or异性,是一道简单的加权并查集

解题报告:

1、关系:`

node[x].relation = 0 ; //与根节点同性


node[x].relation = 1 ; //与根节点异性


2、并查集路径压缩时维护关系:

node[x].relation = (node[x].relation + node[father].relation) % 2


3、两个集合合并时通过向量找出两者root之间的关系:

node[ry].relation = (node[x].relation+1-node[y].relation) % 2;


代码:

import java.util.Scanner;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
* Created by hms on 2017/3/28.
*/
public class Main {
private static final int N = 2010;
public static Node node[] = new Node
;

public static int find(int x) {
if (node[x].pre == x) return x;
int father = node[x].pre;
node[x].pre = find(father);
node[x].relation = (node[x].relation + node[father].relation) % 2;
return node[x].pre;
}

public static void main(String[] args) {
int N;
Scanner scanner = new Scanner(System.in);
N = scanner.nextInt(); //N组
for (int i = 0; i < N; ++i) {

int n = scanner.nextInt(); //有n种昆虫

//初始化
for (int j = 0; j < n + 5; ++j) {
node[j] = new Node();
node[j].pre = j;
node[j].relation = 0;
}

int m = scanner.nextInt(); //m次输入

boolean flag = true;
for (int j = 0; j < m; ++j) {

int x = scanner.nextInt();
int y = scanner.nextInt();
int rx = find(x);
int ry = find(y);
if (rx == ry) {
if (node[x].relation == node[y].relation) {
flag = false;
}
} else {
node[ry].pre = rx;
node[ry].relation = (node[x].relation+1-node[y].relation) % 2;
}
}
if(flag) {
System.out.print("Scenario #");
System.out.print(i+1);
System.out.println(":");
System.out.println("No suspicious bugs found!");
} else {
System.out.print("Scenario #");
System.out.print(i+1);
System.out.println(":");
System.out.println("Suspicious bugs found!");
}
if (i != N - 1) {
System.out.println();
}
}
}
}
class Node {
int pre;
int relation;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  加权并查集