ZOJ 3204: Connect Them

 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=3367

 

 

#include <iostream>
#include <algorithm>
#include <limits>
#include <queue>
using namespace std;
const int MAXN = 105, INF = numeric_limits<int>::max();
typedef pair<int, int> PII;
typedef vector<PII> VPII;
int parent[MAXN];
int T, n, tot;
int Find(int x)//finds the subset of the x-th element and
{
    //updates its predecessors for furture efficiency
    return (parent[x] == x) ? x : parent[x] = Find(parent[x]);
}
void Union(int x, int y)//units two subsets in to a single subset,
{
    //called when they should share the same parent
    parent[Find(x)] = Find(y);
}
struct Edge
{
    int from, to, cost;
    Edge() {};
    Edge(int f, int t, int c) :from(f), to(t), cost(c)
    {

    };
    friend bool operator<(const Edge &e, const Edge &f)
    {
        if (e.cost != f.cost)return e.cost<f.cost;
        if (e.from != f.from)return e.from<f.from;
        return e.to<f.to;
    };
} edge[MAXN*MAXN / 2];
struct cmp
{
    bool operator()(const PII & x, const PII & y)
    {
        if (x.first != y.first)return x.first>y.first;
        return x.second>y.second;
    }
};

priority_queue<PII, VPII, cmp> Q;
bool Kruskal()
{
    /**initialization*/
    for (int i = 1; i <= n; i++) //the index of an element represents the subset it belongs to,
        parent[i] = i;              //so initially itself
    while (!Q.empty())Q.pop();
    sort(edge, edge + tot);
    int counter = 0;
    for (int i = 0; i<tot; i++)
    {
        int u = Find(edge[i].from), v = Find(edge[i].to);
        if (u != v)
        {
            Q.push(make_pair(edge[i].from, edge[i].to));
            parent[u] = v;
            counter++;
        }
    }
    if (counter == n - 1)
        return true;
    return false;
}
int main()
{
    cin >> T;
    while (T--)
    {
        tot = 0;
        cin >> n;
        /**add edges*/
        int t;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
            {
                scanf("%d", &t);
                if (i<j&&t)edge[tot++] = Edge(i, j, t);
            }

        /**Kruskal*/
        if (Kruskal())
        {
            bool f = true;
            while (!Q.empty())
            {
                auto tmp = Q.top();
                if (f)f = false;
                else cout << ' ';
                printf("%d %d", tmp.first, tmp.second);
                Q.pop();
            }
            printf("\n");
        }
        else printf("-1\n");
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/zjnu/p/7226400.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值