题目链接:poj 1308 Is It A Tree?
题目大意:给出一些点的关系,判断是否是一颗树。
解题思路:并查集,如果两个点之间先前已经联通则说明不是一棵树。
注意几个坑点:
1,空树是一棵树;2,相同的两个点间存在两条或者多条边也是不行的;3,形成环是不行的;4,森林是不行的。
#include <stdio.h>
#include <string.h>
#include <vector>
#include <set>
using namespace std;
const int N = 1e6+5;
struct edge {
int u, v;
edge (int u, int v) {
this->u = u;
this->v = v;
}
friend bool operator < (const edge& a, const edge& b) {
if (a.u != b.u) return a.u < b.u;
return a.v < b.v;
}
};
int n, f[N];
vector<edge> g;
set<int> vis;
int getfar (int x) {
return x == f[x] ? x : f[x] = getfar(f[x]);
}
bool init () {
int a, b;
n = 0;
g.clear();
vis.clear();
while (scanf("%d%d", &a, &b) == 2 && a + b) {
if (a == -1 && b == -1) return false;
n = max(n, max(a, b));
g.push_back(edge(a, b));
vis.insert(a);
vis.insert(b);
}
for (int i = 0; i <= n; i++)
f[i] = i;
return true;
}
bool judge () {
for (int i = 0; i < g.size(); i++) {
int a = g[i].u, b = g[i].v;
int p = getfar(a), q = getfar(b);
if (p == q) return false;
f[q] = p;
}
int tmp = getfar(n);
for (set<int>::iterator i = vis.begin(); i != vis.end(); i++)
if (getfar(*i) != tmp) return false;
return true;
}
int main () {
int cas = 1;
while (init()) {
printf("Case %d is %s\n", cas++, judge()? "a tree." : "not a tree.");
}
return 0;
}
分享到:
相关推荐
poj 1308 Is It A Tree_.md
poj2492 A Bug's Life并查集应用的扩展,希望可以给大家带来用处
poj 1909 Marbles on a tree.md
POJ 1988 并查集。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
POJ3273 Monthly Expense题解 题目分析: 给出N个数,要求你合并连续的数,使其合并在满足不差过M个合并后的集合的时候,不超过M个集合的和的最大值最小。
北大POJ1004-Financial Management 解题报告+AC代码
这份代码用C++实现了经典算法并查集,来源于poj题目1182
poj 1611 The Suspects 代码 并查集的应用
北大POJ2525-Text Formalization【TrieTree】 解题报告+AC代码+测试数据 http://hi.csdn.net/!s/XW4FQ3
并查集基础 acm 算法 poj oi 并查集基础.ppt
北大POJ2255-Tree Recovery 解题报告+AC代码
POJ1089 并查集可以解决 并查集加路径压缩
poj 2201 Cartesian Tree.md
POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类
北大POJ2513-Colored Sticks【TrieTree+MergeSet+EulerPath】 解题报告+AC代码
数据结构并查集的相关资料,包括几篇并查集的论文,还有POJ上面几道关于并查集的题目的源代码
北大POJ1584-A Round Peg in a Ground Hole 解题报告+AC代码
poj 2409 Let it Bead.md
北大POJ2031-Building a Space Station【Prim+计算几何】 POJ2031-Building a Space Station【Prim+计算几何】
Give a tree with n vertices,each edge has a length(positive integer less than 1001). Define dist(u,v)=The min distance between node u and v. Give an integer k,for every pair (u,v) of vertices is ...