练习四1004

来源:互联网 发布:linux最大连接数65536 编辑:程序博客网 时间:2024/05/21 06:23

题意:在乡村之间修公路,给定n个乡村,然后是n行,每行给定两个数代表了两个乡村和第三个数代表这两个村之间修路的费用,求使公路联通的修路的最小的费用。

思路:根据kruskal算法,写find函数,再写一个结构体,再写一个merge函数,把两村之间的权值排序求和即可。

感悟:好好学算法,做题也很爽。

AC代码:

#include<iostream>#include<stdio.h>#include<algorithm>using namespace std;const int N=1005;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;    while(scanf("%d",&n),n)    {        for(int i=1;i<=n;i++)            father[i]=i;    n=n*(n-1)/2;    for(int i=0;i<n;i++)        scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].v);    sort(e,e+n,cmp);    int res=0;    for(int i=0;i<n;i++)    {        int x=find(e[i].x);        int y=find(e[i].y);        if(x!=y)        {            res+=e[i].v;            father[x]=y;        }    }    printf("%d\n",res);    }    return 0;}

0 0