算法设计分析实验三——贪心求最小生成树

#include<bits/stdc++.h>
#include<set>
#include<cstdio>
#include<iomanip>
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#define pb push_back
#define ll long long
#define fi first
#define se second
#define PI 3.14159265
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1
#define eps 1e-7
#define pii pair<int,int>
typedef unsigned long long ull;
const int mod=1e3+5;
const ll inf=0x3f3f3f3f3f3f3f;
const int maxn=1e3+5;
using namespace std;
struct edge
{
    int l,u,v;
    bool operator<(const edge b)const
    {
        return l<b.l;
    }
};
multiset<edge>et;
int fa[maxn],n,m;
int f(int x)
{
    if(x==fa[x])
    {
        return fa[x];
    }
    return fa[x]=f(fa[x]);
}
void _merge(int x,int y)
{
    fa[f(y)]=f(x);
}
void init(int num)
{
    for(int i=1;i<=num;i++)
    {
        fa[i]=i;
    }
}
int main()
{
     ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>n>>m;
    init(n);
    for(int i=1;i<=m;i++)
    {
        edge tmp;
        cin>>tmp.v>>tmp.u>>tmp.l;
        et.insert(tmp);
    }
    cout<<endl;
    int num=n-1,len=0;
    while(num--)
    {
        bool flag=true;

        while(flag)
        {

            edge tmp=*et.begin();
           // cout<<tmp.u<<" "<<tmp.v<<" "<<tmp.l<<endl;
            if(f(tmp.u)!=f(tmp.v))
            {
                len+=tmp.l;
                cout<<tmp.u<<" "<<tmp.v<<" "<<tmp.l<<endl;
                flag=false;//cout<<"SSS"<<endl;
                _merge(tmp.v,tmp.u);
            }

             et.erase(et.begin());
        }
    }
    cout<<"需要用到的边的总长度为"<<len<<endl;
    return 0;
}
/*
5 8
1 3 3
1 2 2
1 4 3
1 5 4
3 5 3
4 5 5
2 4 3
3 2 1
*/

 

posted @ 2018-05-31 11:27  lhclqslove  阅读(172)  评论(0编辑  收藏  举报