openjudge_简单英文题_33:Is It a Tree

题目

33:Is It a Tree
总时间限制: 1000ms 内存限制: 65536kB
描述
Given edges of a graph with N nodes. Check whether it is a tree.

输入
First line: one positive integers N (N <= 100).
Next N lines: an N*N 0/1 matrix A={a[i][j]}, indicating whether there exists an edge between node i and node j (a[i][j]=1) or not (a[i][j]=0).
输出
One integer, 1 if the graph is a tree, or 0 otherwise.
样例输入
4
0 1 0 1
1 0 1 0
0 1 0 0
1 0 0 0
样例输出
1

翻译

题目:它是一棵树吗
描述:
给定具有N个节点的图的边。检查它是否是一棵树。
输入:
第一行:一个正整数N(N<=100)。
接下来的N行:一个N*N 0/1矩阵A={A[i][j]},表示节点i和节点j之间是否存在边(A[i][j]=1)(A[i][j]=0)。
输出:
一个整数,如果图是树,则为1,否则为0。

代码

//如果还没合并就已经是同根,那就是环
#include <bits/stdc++.h>
using namespace std;
int n,
f[101],//父点
m;
bool d[101][101],//两点链接否
ans;//是否树
int find(int x){
if(f[x]!=x&&f[x]!=1)f[x]=find(f[x]);
return f[x];
}
void he(int a,int b){
int fa=find(a);
int fb=find(b);
if(fa!=fb)f[b]=fa;
}
int main(){
//freopen(“data.cpp”,“r”,stdin);
cin>>n;
for(int i=1;i<=n;i++){
f[i]=i;
for(int j=1;j<=n;j++)cin>>d[i][j];
}
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
if(d[i][j]){//有链接
m++;//多个边
if(f[i]= =f[j])//没合并就同根
{ans=1;break;}//环,非树
else he(i,j);
}
if(ans)cout<<0;
else if(m==n-1)cout<<1;
else cout<<0;
return 0;
}

总结

并查集可以判断是否环
就是有链接的两点没有合并就同根,就是环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值