码迷,mamicode.com
首页 > 其他好文 > 详细

51nod--1212 无向图最小生成树

时间:2018-05-10 23:40:00      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:pid   中间   size   lse   div   技术分享   基础   ble   int   

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
 
 
N个点M条边的无向连通图,每条边有一个权值,求该图的最小生成树。
 
Input
第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000)
第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)
Output
输出最小生成树的所有边的权值之和。
Input示例
9 14
1 2 4
2 3 8
3 4 7
4 5 9
5 6 10
6 7 2
7 8 1
8 9 7
2 8 11
3 9 2
7 9 6
3 6 4
4 6 14
1 8 8
Output示例
37

就是最简单的求最小生成树,用并查集
/*
    data:2018.05.10
    author:gsw
    link:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1212
    account:2684524947@qq.com

*/
#define ll long long
#define IO ios::sync_with_stdio(false);

#include<iostream>
#include<algorithm>
#include<math.h>
#include<stdio.h>
#include<string.h>
using namespace std;

class Edge
{
public:
    int a,b,c;
};
Edge edge[50005];
int pre[1005];int n,m;

bool camp(Edge aa,Edge bb)
{
    return aa.c<bb.c;
}
int Find(int x)
{
    int r=x;
    while(r!=pre[r])
        r=pre[r];
    int i=x,j;
    while(pre[i]!=r)
    {
        j=pre[i];
        pre[i]=r;
        i=j;
    }
    return r;
}
void init()
{
    memset(edge,0,sizeof(edge));
    for(int i=1;i<=n;i++)
        pre[i]=i;
}
int mix(int x,int y)
{
    //cout<<x<<" y="<<y<<endl;
    int fx=Find(x),fy=Find(y);
    //cout<<fx<<" fy="<<fy<<endl;
    if(fx!=fy)
    {
        pre[fy]=fx;
        return 1;
    }
    return 0;
}
ll kusal()
{
    sort(edge,edge+m,camp);
    ll ans=0;int js=0;
    for(int i=0;i<m;i++)
    {

        if(mix(edge[i].a,edge[i].b))
        {
            //cout<<"ans="<<ans<<endl;
            ans+=edge[i].c;
            js++;
        }
        if(js==(n-1))break;
    }
    return ans;
}
int main()
{

    scanf("%d%d",&n,&m);
    init();
    int a,b,c;
    for(int i=0;i<m;i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        edge[i].a=a;edge[i].b=b;edge[i].c=c;
    }
    cout<<kusal()<<endl;
    return 0;
}

 

51nod--1212 无向图最小生成树

标签:pid   中间   size   lse   div   技术分享   基础   ble   int   

原文地址:https://www.cnblogs.com/fantastic123/p/9021895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!