Agri-Net - minimum spanning tree problem template (matrix input)

Topic Link

Meaning of the questions:

Give you a matrix representing spent ij connections needed to obtain minimum cost

answer:

Bare minimum spanning tree board

Matrix can handle input

 

Code:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 105;
int f[maxn];
int x[maxn],y[maxn];
int n,cnt,m;
struct node
{
    int u,v;
    int w;
    bool operator < (const node &a)const
    {
        return w<a.w;
    }
} edge[maxn*maxn];

int Find(int x)
{
    return x==f[x]?x:f[x]=Find(f[x]);
}
void add(int u,int v,int w)
{
    edge[cnt].u=u;
    edge [cnt] .v = v;
    edge[cnt++].w=w;
}

int kruskal()
{
    int ans=0;
    for(int i=0; i<=n; i++)f[i]=i;
    sort(edge,edge+cnt);
    for(int i=0; i<cnt; i++)
    {
        int x=edge[i].u;
        int y=edge[i].v;
        int fx=Find(x);
        int fy=Find(y);
        if(fx!=fy)
        {
            f[fx]=fy;
            ans+=edge[i].w;
        }
    }
    return years;
}

int main ()
{
    while(~scanf("%d",&n))
    {
        cnt=0;
        for(int i=0; i<=n; i++)f[i]=i;

        for(int i=1; i<=n; i++)for(int j=1; j<=n; j++)
        {
            int x;
            scanf("%d",&x);
            add(i,j,x);
        }
        printf("%d\n",kruskal());
    }



    return 0;
}
kruskal

 

 

Guess you like

Origin www.cnblogs.com/j666/p/11616989.html