POJ 2492 A Bug's Life
2017-05-14 11:42
155 查看
题目链接:http://poj.org/problem?id=2492
题目大意:给出n种昆虫,并给出这些昆虫中配对的情况,让你判断有没有同性恋的虫子。
题目理解:每种昆虫之间都有必然的关系——同性or异性,是一道简单的加权并查集
解题报告:
1、关系:`
2、并查集路径压缩时维护关系:
3、两个集合合并时通过向量找出两者root之间的关系:
代码:
题目大意:给出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; }
相关文章推荐
- poj 2492 A Bug's Life
- POJ - 2492 A Bug's Life
- POJ 2492 || HDU 1829:A Bug's Life(并查集)
- poj 2492 - A Bug's Life(并查集)
- POJ 2492 A Bug's Life(并查集)
- POJ 2492 A Bug's Life 带权并查集!
- POJ 2492 A Bug's Life【并查集的简单应用同类的判断】
- POJ - 2492 A Bug's Life 种类并查集
- POJ 2492 A Bug's Life(并查集)
- POJ 2492 A Bug's Life(扩展并查集)
- POJ - 2492 A Bug's Life(种类并查集)
- HDU1829&POJ 2492 a bug's life [并查集||二分图染色]
- poj 2492 A Bug's Life (并查集同食物链)
- 【POJ 2492】 A Bug's Life (条件并查集/bfs)
- poj 2492 A Bug's Life 带权并查集
- A Bug's Life(POJ - 2492)种类并查集
- poj 2492 A Bug's Life
- POJ - 2492 -A Bug's Life 【带权并查集讲解】
- POJ 2492 A Bug's Life 简单并查集
- poj 2492 A Bug's Life(种类并查集)