题意简述
给定一些边,边中包括的点编号不一定连续。请判断是否组成一颗树。
数据
输入:
十分奇怪。多组数据,每组数据包含一些点对 ( a , b ) (a,b) (a,b),具体范围不明,反正开 1 e 6 1e6 1e6能过。如果 a = = 0 a==0 a==0且 b = = 0 b==0 b==0表示一组数据结束,如果 a = = − 1 a==-1 a==−1且 b = = − 1 b==-1 b==−1表示所有数据结束。
输出
对于第 i i i组数据,输出"Case i is a tree."(是一颗树),或"Case i is not a tree."(不是的情况)
样例
输入
6 8 5 3 5 2 6 4
5 6 0 0
8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0
3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1
输出
Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree.
思路
显然并查集能过,在学
K
r
u
s
k
a
l
Kruskal
Kruskal的时候我们学会了如何用并查集判定一个树。
但是,这个题目有很多坑点
1.处理输入。。。这个还好了,如果a=0 and b=0就break,如果a=-1 and b=-1就exit(0)
2.有自环的。。。
3.图不一定联通。。。而且可能是森林。。。
4.点不连续,要打 v i s vis vis数组, v i s [ i ] vis[i] vis[i]表示 i i i是否出现过。但是,这个 v i s vis vis每次要 m e m s e t 0 memset0 memset0!!!
5.没有点也是树。。。
6.poj不支持bits/stdc++.h!!!
好了。。。接下来就是我用N次提交换来的AC代码:
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<cstring>
using namespace std;
namespace Flandle_Scarlet
{
#define N 1001000
class DSU//并查集
{
public:
int Father[N],Cnt[N];
void Init()
{
for(int i=0;i<N;++i)
{
Father[i]=i;
Cnt[i]=1;
}
}
int Find(int x)
{
return x==Father[x]?x:Father[x]=Find(Father[x]);
}
void Merge(int x,int y)
{
int ax=Find(x),ay=Find(y);
if (Cnt[ax]<Cnt[ay])
{
Cnt[ay]+=Cnt[ax];
Father[ax]=ay;
}
else
{
Cnt[ax]+=Cnt[ay];
Father[ay]=ax;
}
}
}D;
int Ed[N][2];
bool vis[N];int Max;
int n;
void Input()
{
int i=1;
while(1)//处理输入
{
int a,b;
scanf("%d%d",&a,&b);
if (a==0 and b==0)
{
break;//单个结束
}
if (a==-1 and b==-1) exit(0);//全部结束
Ed[i][0]=a,Ed[i][1]=b;
vis[a]=1,vis[b]=1;//做好标记
Max=max(Max,max(a,b));//最大编号的点
++i;
}
n=i-1;
}
void Yes(int Case)
{
printf("Case %d is a tree.\n",Case);
}
void No(int Case)
{
printf("Case %d is not a tree.\n",Case);
}
void Solve(int Case)
{
if (n==0)//没有点
{
Yes(Case);
return;
}
for(int i=1;i<=n;++i)
{
int u=Ed[i][0],v=Ed[i][1];
if (D.Find(u)==D.Find(v))
{
//环
//(注意这里包含了u==v的情况)
No(Case);
return;
}
D.Merge(u,v);//这个不要忘
}
int ancestor=0;//只能有一个祖先(有多个就是森林了)
for(int i=1;i<=Max;++i)
{
if (vis[i])
{
if (i==D.Find(i))
{
++ancestor;
}
}
}
if (ancestor==1)//只有一个祖先就Yes
{
Yes(Case);
}
else//否则No
{
No(Case);
}
}
void Main()
{
int Case=1;
while(1)
{
D.Init();
memset(vis,0,sizeof(vis));
Input();
Solve(Case);
++Case;
}
}
#undef N //1001000
}
int main()
{
Flandle_Scarlet::Main();
return 0;
}
博客介绍了POJ 1308问题的解决方案,涉及判断给定边是否构成一棵树。内容涵盖题意解析、数据描述、输入输出格式及样例,并讨论了使用并查集解决该问题时需要注意的若干关键点,如处理输入、自环、图的连通性、点的连续性等。
3682

被折叠的 条评论
为什么被折叠?



