题解 | #Is It A Tree?#

Is It A Tree?

http://www.nowcoder.com/practice/1c5fd2e69e534cdcaba17083a5c56335

【基于并查集判断树】
+无环(a->b,b->a):getRoot(a)!=b
+无多入(a->b,c->b):parent[b]==b
+必连通:计算连通子图数

#include<iostream>
#include<map>
#include<string>
using namespace std;
int getRoot(map<int,int> parent,int i){
    while(parent[i]!=i){
        i = parent[i];
    }
    return i;
}
int main(){
    
    int a,b;
    for(int i=1;;i++){
        map<int,int> parent;
        bool isTree = true;
        while(1){
            cin>>a>>b;
            if(a==0&&b==0) break;
            if(a==-1&&b==-1) return 0;
            if(parent.find(a)==parent.end()) parent[a] = a;
            if(parent.find(b)==parent.end()) parent[b] = b;
            
            if(parent[b]==b && getRoot(parent,a)!=b){
                parent[b] = a;
            } else {
                isTree = false;
            }
        }
        int counter = 0;
        map<int,int>::iterator it = parent.begin();
        while(it!=parent.end()){
            if(it->first==it->second) counter++;
            it++;
        }
        if(counter>1) isTree = false;
        string ans = isTree?"":"not ";
        cout<<"Case "<<i<<" is "<<ans<<"a tree."<<endl;
    }
    return 0;
}


全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 13:05
点赞 评论 收藏
分享
投递长鑫存储等公司7个岗位
点赞 评论 收藏
分享
06-07 19:59
门头沟学院 C++
补药卡我啊😭:都快15年前的了还在11新特性
你的简历改到第几版了
点赞 评论 收藏
分享
仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
这不纯纯作弊了吗😢😢😢
编程界菜鸡:信这个的这辈子有了,这智商你靠啥都没用
你找工作的时候用AI吗?
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务