POJ 1861 Network

题目链接:

http://poj.org/problem?id=1861

题目大意:

Andrew计划搭建一个网络,有n个集线器且每个集线器必须能通过网线连接其他集线器,现有不同长度网线供选择且网线越短越便宜,要求Andrew所设计的方案必须确保最长的一个网线是所有方案中最小的。

题目思路:

其实就是求这个图的最小生成树的最大边,然后将加入到生成树中的每条边都输出出来。

注:题目的样例数据是错的。

 

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
#define INF 0xfffffff
#define maxn 15005

struct Edge
{
    int  s, e, w;
    Edge(int s=0,int e=0,int w=0):s(s), e(e), w(w) {}
    bool friend operator < (Edge A, Edge B)
    {
        return A.w < B.w;
    }
}P[maxn];

int m, n, Par[maxn];
int GetPar(int a);
void Init();
void Meger(int a,int b);
void Kruskal();

int main()
{
    while(cin >> n >> m)
    {
        Init();

        for(int i=0; i<m; i++)
        {
            int s, e, w;
            cin >> s >> e >>w;
            P[i] = Edge(s,e,w);
        }
        sort(P, P+m);
        Kruskal();
    }
}

int GetPar(int a)
{
    if(Par[a] != a)
        return Par[a] = GetPar(Par[a]);
    return a;
}

void Init()
{
    for(int i=0; i<=n; i++)
        Par[i] = i;
}

void Meger(int a,int b)
{
    Par[GetPar(a)] = GetPar(b);
}

void Kruskal()
{
    Edge Ans[1005];
    int k = 0;
    for(int i=0; i<m; i++)
    {
        if(GetPar(P[i].s) != GetPar(P[i].e) )
        {
            Meger(P[i].s, P[i].e);
            Ans[k++] = P[i];
        }
    }

    cout << Ans[k-1].w << endl;
    cout << n-1 << endl;

    for(int i=0; i<k; i++)
    {
        cout << Ans[i].s <<" " << Ans[i].e << endl;
    }

}

 

posted @ 2015-01-14 16:04  向前走丶不回首  阅读(178)  评论(0编辑  收藏  举报