点击打开链接poj 1308
思路:并查集
分析:如果是一棵树,那么就只能有唯一的一个根节点。所以我们只要在输入的时候判断两个元素能否合并即可,如果输入的两个元素的根节点相同肯定是不满足的,其它还有“空树”“森林”都不算是树。所以最后还要判断一下是否是森林还是树。注意句子末尾有个“.”
输入的边可能是自环,这个是一个trick
注意以下数据
1: 0 0 空树是一棵树。
2: 1 1 0 0 不是树 1 和 1的根据点相同
3: 1 2 1 2 0 0 不是树,第二个开始1 和 2的根节点相同不是树
4: 1 2 2 3 4 5 不是树 森林不算是树
5: 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1 最后的9 和1根节点相同不是树
6: 1 2 2 1 0 0 不是树
代码:
#include<set>
#include<cstdio>
#include<cstring>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 1000010;
int father[MAXN];
set<int>s;
void init(){
s.clear();
for(int i = 1 ; i < MAXN ; i++){
father[i] = i;
}
}
int find(int x){
if(father[x] != x)
father[x] = find(father[x]);
return father[x];
}
int main(){
int cas = 1;
int x , y;
while(scanf("%d%d" , &x , &y) && x >= 0){
printf("Case %d " , cas++);
if(x+y == 0)
puts("is a tree.");
else{
init();
father[y] = x;
// 如果出现自环的时候x == y的时候就不算树
bool isOk = (y != x ? true : false);
s.insert(x);
s.insert(y);
while(scanf("%d%d" , &x , &y) && x+y){
s.insert(x);
s.insert(y);
int fx = find(x);
int fy = find(y);
if(fy == fx){
isOk = false;
}
else{
father[fy] = fx;
}
}
if(!isOk)
puts("is not a tree.");
else{
set<int>::iterator it = s.begin();
int root = find(*it);
for(it++; it != s.end() ; it++){
if(root != find(*it)){
isOk = false;
break;
}
}
if(isOk)
puts("is a tree.");
else
puts("is not a tree.");
}
}
}
return 0;
}
分享到:
相关推荐
poj 1308 Is It A Tree_.md
poj 1909 Marbles on a tree.md
POJ3273 Monthly Expense题解 题目分析: 给出N个数,要求你合并连续的数,使其合并在满足不差过M个合并后的集合的时候,不超过M个集合的和的最大值最小。
北大POJ1004-Financial Management 解题报告+AC代码
北大POJ2525-Text Formalization【TrieTree】 解题报告+AC代码+测试数据 http://hi.csdn.net/!s/XW4FQ3
北大POJ2255-Tree Recovery 解题报告+AC代码
poj 2201 Cartesian Tree.md
北大POJ2513-Colored Sticks【TrieTree+MergeSet+EulerPath】 解题报告+AC代码
POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类
poj 2409 Let it Bead.md
北大POJ1584-A Round Peg in a Ground Hole 解题报告+AC代码
北大POJ2031-Building a Space Station【Prim+计算几何】 POJ2031-Building a Space Station【Prim+计算几何】
北大POJ3414-Pots 解题报告+AC代码
北大POJ2983-Is the Information Reliable【差分约束+优化Bellman】 解题报告+AC代码
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 ...
北大POJ1691-Painting A Board 【拓扑+DFS】 解题报告+AC代码
北大POJ1942-Paths on a Grid 解题报告+AC代码
poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题...
具体题目参考: http://poj.org/userstatus?user_id=tanzhangwen 本压缩文件里面有所有已经Accepted的题目的源码,主要语言为c/c++,少量java
It earns a profit px for each product x∈Prod sold by a deadline dx that is measured as an integral number of time units starting from the moment the sale begins. Each product takes precisely one ...