您的位置:首页 > 其它

Problem4-1004

2016-07-03 22:08 232 查看
简单题意:给你一些镇子,和镇子之间的距离,现在要修一条路,把所有镇子连起来,求路的最短距离。

解题思路:最小生成树问题,我采用的还是KRUSKAL是第一题的简化版,详情请看第一题。

代码如下:

#include <iostream>  

#include <fstream>  

#include <algorithm>  

using namespace std;  

const int N = 105;  

int father
;  

int find(int x)   

{  

    if (x != father[x])  

        father[x] = find(father[x]);  

    return father[x];  

}  

struct edge  

{  

    int x, y, v;  

}e[N*(N - 1) / 2];  

int cmp(edge e1, edge e2)   

{  

    return e1.v<e2.v;  

}  

  

int main()  

{  

    //ifstream cin("aaa.txt");  

    int n;  

    while (cin >> n&&n)  

    {  

        for (int i = 0; i <= n; ++i)  

            father[i] = i;  

        n = n*(n - 1) / 2;  

        for (int i = 0; i<n; i++)  

            cin>>e[i].x>>e[i].y>>e[i].v;  

        sort(e, e + n, cmp);  

        int ans = 0;  

        for (int i = 0; i < n; ++i)  

        {  

            int x = find(e[i].x);  

            int y = find(e[i].y);  

            if (x != y)  

            {     

                ans += e[i].v;  

                father[x] = y;    

            }  

        }  

        cout << ans << endl;  

    }  

    return 0;  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: