最小生成树(Kruskal算法)贪心算法 利用并查集

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include 
#include 

#define NUM 1000
#define maxint 10000000
#define INF 0x3f3f3f3f
using namespace std;

int c[NUM][NUM];//用邻接矩阵存储边和权
int dist[NUM];

struct graph
{
    int u,v , cost;
    void set(int a ,int b ,int c)
    {
        this->u = a;
        this->v = b;
        this->cost = c;
    }
};

bool cmp(const graph a , const graph b)
{
    return a.cost>v_num>>e_num && (v_num || e_num))
    {
        graph d[e_num+1];
        int Father[v_num+1];
        for(int i = 1;i<=v_num;i++)
        {
            Father[i] = i;
        }
        for(int i = 1;i<=e_num;i++)
        {
            int x, y , weight;
            cin>>x>>y>>weight;
            
            d[i].set(x, y, weight);
        }
        sort(d+1,d+e_num+1,cmp);
        int sum = 0;
        for(int i = 1;i<=e_num;i++)
        {
            if(Union(d[i].u, d[i].v, Father))
            {
                cout<

输入:

6 10
1 2 6
1 3 1
1 4 5
2 3 5
2 5 3
3 4 5
3 5 6
3 6 4
4 6 2
5 6 6

输出:

1  3
4  6
2  5
3  6
2  3
15

你可能感兴趣的:(浙大ACM)