【每日一题】 Is It A Tree?

Is It A Tree?

https://ac.nowcoder.com/acm/problem/105905

题意:

思路:



#include <cstdio>
#include <set>
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
int fa[N],in[N];
int m;//边的数量 
bool isTree;
set<int> s;
void init(){
    for(int i = 1;i < N;i++) fa[i] = i,in[i] = 0;
    m = 0;
    isTree = 1;
    s.clear();
}
int find(int x){
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}
bool merge(int x,int y){
    int fx = find(x),fy = find(y);
    if(fx == fy) return 0;
    fa[fx] = fy;
    return 1;
}
void check(){
    if(m != s.size() - 1 && s.size() != 0) isTree = 0;
}
int main(){
    int u,v,cas = 1;
    init();
    while(~scanf("%d%d",&u,&v)){
        if(u < 0 && v < 0) break;
        if(u == 0 && v == 0){
            check();
            if(isTree){
                printf("Case %d is a tree.\n",cas++);
            }else{
                printf("Case %d is not a tree.\n",cas++);
            }
            init();
        }else{
            m++;
            isTree &= merge(u,v);
            if(++in[v] > 1) isTree = false;
            s.insert(u),s.insert(v);
        }
    }
}
每日一题 文章被收录于专栏

每题一题题目

全部评论

相关推荐

冷艳的小师弟在看机会:jd测评乱点直接被挂了,哭死~
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务