1004-D专题四

来源:互联网 发布:360浏览器精简优化版 编辑:程序博客网 时间:2024/06/11 08:50

1,.题意:给出镇子之间距离,修路使它们联通,求最小的修路距离

2.思路:最小生成树问题,用的kruskal算法,跟第一个题类似

3.感想:觉得kruskal理解起来很简单,用起来也好用

#include <iostream>#include <algorithm>using namespace std;const int N = 105;int father[N];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(){    int n,x,y;    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)        {             x = find(e[i].x);             y = find(e[i].y);            if (x != y)          {                ans += e[i].v;                father[x] = y;            }        }        cout << ans << endl;    }    return 0;}


0 0
原创粉丝点击