zoukankan      html  css  js  c++  java
  • 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;
        }
    
    }
  • 相关阅读:
    POJ 1703 Find them, Catch them
    POJ 2236 Wireless Network
    POJ 2010 Moo University
    POJ 2184 Cow Exhibition
    POJ 3280 Cheapest Palindrome
    POJ 3009 Curling 2.0
    POJ 3669 Meteor Shower
    POJ 2718 Smallest Difference
    POJ 3187 Backward Digit Sums
    POJ 3050 Hopscotch
  • 原文地址:https://www.cnblogs.com/chenchengxun/p/4224171.html
Copyright © 2011-2022 走看看