poj 1308 Is It A Tree?
生活随笔
收集整理的這篇文章主要介紹了
poj 1308 Is It A Tree?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 題意: 給出一些邊,由所給出的邊能否構成一棵樹.(節點數<100)
// 思路: n個頂點的樹具有3個特點:連通,不含環,恰好包含n-1條邊.只要有任意兩個,就能推導出第3個
// 所以我們可以通過是否連通和不含環來判斷可以構成樹.
// 不含環: 通過并查集,如果邊a->b, a和b的祖先結點都一樣,則是有環,包括a->a,和 a->b 重復出現,
// 連通: 只有一個根結點
#include <iostream> //并查集
using namespace std;
#define maxn 1000
int p[maxn],isNode[maxn];
int find(int x)
{
return p[x]==x ? x : p[x]=find(p[x]);
}
int main()
{
int t=1,a,b;
while(cin>>a>>b&&a!=-1) // a->b
{
if(a==0) //只有 0 0 ,空樹也是一棵樹
{
printf("Case %d is a tree.\n",t++);
continue;
}
for(int i=1;i<maxn;++i)
{
p[i]=i;
isNode[i]=0;
}
int isTree=1,tail=0;
while(a!=0)
{
if(isTree)
{
int x=find(a),y=find(b);
if(x==y) //說明存在環
{
isTree=0;
}
else
{
p[y]=x; //a->b
isNode[a]=isNode[b]=1; //標志結點
tail=max(tail,max(a,b)); //結點的下標并不是順序增加 1
}
}
cin>>a>>b;
}
if(!isTree)
printf("Case %d is not a tree.\n",t++);
else
{
int roots=0;
for(int i=1;i<=tail;i++)
{
if(isNode[i]&&p[i]==i) //找到一根結點
{
roots++;
if(roots>1)
break;
}
}
if(roots==1)
printf("Case %d is a tree.\n",t++);
else
printf("Case %d is not a tree.\n",t++); //沒有根結點,或者不只一個根結點
}
}
return 0;
}
// 思路: n個頂點的樹具有3個特點:連通,不含環,恰好包含n-1條邊.只要有任意兩個,就能推導出第3個
// 所以我們可以通過是否連通和不含環來判斷可以構成樹.
// 不含環: 通過并查集,如果邊a->b, a和b的祖先結點都一樣,則是有環,包括a->a,和 a->b 重復出現,
// 連通: 只有一個根結點
#include <iostream> //并查集
using namespace std;
#define maxn 1000
int p[maxn],isNode[maxn];
int find(int x)
{
return p[x]==x ? x : p[x]=find(p[x]);
}
int main()
{
int t=1,a,b;
while(cin>>a>>b&&a!=-1) // a->b
{
if(a==0) //只有 0 0 ,空樹也是一棵樹
{
printf("Case %d is a tree.\n",t++);
continue;
}
for(int i=1;i<maxn;++i)
{
p[i]=i;
isNode[i]=0;
}
int isTree=1,tail=0;
while(a!=0)
{
if(isTree)
{
int x=find(a),y=find(b);
if(x==y) //說明存在環
{
isTree=0;
}
else
{
p[y]=x; //a->b
isNode[a]=isNode[b]=1; //標志結點
tail=max(tail,max(a,b)); //結點的下標并不是順序增加 1
}
}
cin>>a>>b;
}
if(!isTree)
printf("Case %d is not a tree.\n",t++);
else
{
int roots=0;
for(int i=1;i<=tail;i++)
{
if(isNode[i]&&p[i]==i) //找到一根結點
{
roots++;
if(roots>1)
break;
}
}
if(roots==1)
printf("Case %d is a tree.\n",t++);
else
printf("Case %d is not a tree.\n",t++); //沒有根結點,或者不只一個根結點
}
}
return 0;
}
轉載于:https://www.cnblogs.com/mjc467621163/archive/2011/07/20/2112182.html
總結
以上是生活随笔為你收集整理的poj 1308 Is It A Tree?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是spring(转载)
- 下一篇: POJ1459-Power Networ