POJ 1308 Is It A Tree?和HDU 1272 小希的迷宫

POJ题目网址:http://poj.org/problem?id=1308

HDU题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=1272

并查集的运用,如果想要形成一棵树,那么我们应该只能有一个根,并查集联合次数为节点数-1。

//Asimple
//#include <bits/stdc++.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cctype>
#include <cstdlib>
#include <stack>
#include <cmath>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <limits.h>
#include <time.h>
#define INF 0xfffffff
#define mod 10007
#define swap(a,b,t) t = a, a = b, b = t
#define CLS(a, v) memset(a, v, sizeof(a))
#define debug(a)  cout << #a << " = "  << a <<endl
#define abs(x) x<0?-x:x
using namespace std;
typedef long long ll;
const int maxn = 100005;
int fa[maxn];
//int re[maxn]; 
int n, m, T, x, y, num, len;
set<int> s;
bool f;

void init() {
    for(int i=0; i<maxn; i++) fa[i] = i;
    f = false;
    len = 0;
    s.clear();
}

int find(int x) {
    return fa[x]==x?x:fa[x]=find(fa[x]);
}

void make_set(int x, int y) {
    if( x==y ) f = true;
    x = find(x);
    y = find(y);
    if( x!=y ){
        fa[x] = y;
        len ++;
    } else f = true;
}

void solve() {

}

void input() {
    int cas = 1;
    while( true ) {
        init();
        cin >> x >> y;
        if( x == 0 && y == 0 ) {
//            cout << "Case "<< cas++ <<" ";
//            puts("is a tree.");
            puts("Yes");
            continue;
        }
        if( x==-1 && y==-1 ) break;
        s.insert(x);
        s.insert(y);
        make_set(x, y);
        while( cin >> x >> y ) {
            if( x==0 && y == 0 ) break;
            s.insert(x);
            s.insert(y);
            make_set(x, y);
        }
//        cout << "Case "<< cas++ <<" "; 
        if( len+1 == s.size() && !f ) puts("Yes");
        else puts("No"); 
    }
}

int main() {
    input();
    return 0;
}
原文地址:https://www.cnblogs.com/Asimple/p/6591299.html