HDU1272 小希的迷宫 - 并查集

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

输入需要注意下,其次用set<>集合处理较方便

/* HDU1272 小希的迷宫 http://acm.hdu.edu.cn/showproblem.php?pid=1272 */
#include <iostream> 
#include <stdio.h> 
#include <algorithm> 
#include <memory.h> 
#include <set>
#include <vector>
#include <map>
#include <unordered_map>
using namespace std;

#define N 100002

int fa[N];
int find(int x)
{
    if (x == fa[x])
        return x;
    return fa[x] = find(fa[x]);
}
void merge(int x, int y)
{
    fa[find(y)] = fa[find(x)];
}
struct edge
{
    int u;
    int v;
};
vector<edge> ve;

bool chuli()
{
    set<int> allp;
    allp.clear();

    int minn = N, maxx=0;
    int len = ve.size();
    int i;
    for (i = 0; i < len; i++)
    {
        int u = ve[i].u;
        int v = ve[i].v;
        if (find(u) != find(v))
        {
            merge(u, v);
        }
        else{
            return false;
        }
        allp.insert(u);
        allp.insert(v);
    }
    set<int> sset; 
    sset.clear();

    set<int>::iterator it;
    for (it = allp.begin(); it != allp.end(); it++)
    {
        int tmp = *it;
        sset.insert(find(tmp));
    }
    if ((int)sset.size() > 1)
        return false;
    return true;
}

int main()
{
    //freopen("in", "r", stdin);
    int a, b;
    int i, j;
    ve.clear();
    for (i = 0; i < N; i++)
    {
        fa[i] = i;
    }
    while (scanf("%d%d", &a, &b) != EOF)
    {
        if (a == -1 && b == -1)
            break;
        if (a == 0 && b == 0)
        {
            if (chuli())
                printf("Yes\n");
            else
                printf("No\n");
            ve.clear();
            char s[1];
            gets(s);
            for (i = 0; i < N; i++)
            {
                fa[i] = i;
            }
        }
        else{
            edge et;
            et.u = a;
            et.v = b;
            ve.push_back(et);
        }
    }
    return 0;
}

你可能感兴趣的:(HDU1272 小希的迷宫 - 并查集)