代码实现
#include <cstdio>
#include <unordered_map>
using namespace std;
const int maxn = 10010;
unordered_map<int,int> father;
unordered_map<int,int> inDegree;
int find(int x){
if(father[x] == x){
return x;
}else{
int root = find(father[x]);
father[x] = root;
return root;
}
}
void Union(int u,int v){
int fatherU = find(u);
int fatherV = find(v);
if(fatherU != fatherV){
father[fatherV] = fatherU;
}
return;
}
int main(){
int u,v;
bool isTree=true;
int cnt=1;
while(scanf("%d %d",&u,&v)!=EOF&&u!=-1&&v!=-1){
if(u==0&&v==0){
int check=0;
int root;
for(unordered_map<int,int>::iterator it=father.begin();it!=father.end();it++){
if(find(it->first)==it->first){
root = it->second;
check++;
}
}
if(check>1){
isTree=false;
}else{
if(inDegree.count(root)!=0){
isTree=false;
}
}
if(isTree){
printf("Case %d is a tree.\n",cnt);
}else{
printf("Case %d is not a tree.\n",cnt);
}
father.clear();
inDegree.clear();
isTree=true;
cnt++;
}else{
if(father.count(u)==0){
father[u]=u;
}
if(father.count(v)==0){
father[v]=find(u);
}else{
Union(u,v);
}
inDegree[v]++;
if(inDegree[v]>1){
isTree=false;
}
}
}
return 0;
}
码后反思
- 这道题我第一次做,做错了,因为没有考虑到根结点
root的入度一定要为0,所以没有过题! - 这道题其实就是判断两个方面:
- 图连通;
- 根节点入度为0,其他结点入度为1;
其中要先判断第一个图连通,再判断根节点的入度为0。因为不连通的话,就会有很多根结点了。。。