Constructing Roads-- minimum spanning tree

Topic Link

 

Meaning of the questions:

There are N villages, numbered from 1 to N. N is now required between the villages road, so communication can be between any two villages. Said A, B are two villages communication,

If and only if A and B are directly connected with a road, the presence or village C, such that a road connecting two villages between A and C, and there is a connection between C and B path.

Between some villages have been known way a direct connection, the construction of some of the test path such that all the villages are connected, and the total length of the shortest road.

 

The distance between two given points in a matrix and a given number of two lines each pp showing two paths has been repaired villages

answer:

The bare minimum spanning tree board

As long as the road has been built right value is set to 0

 

Code:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 110;
int f[maxn];
int n,cnt,q;
struct node
{
    int u,v,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);
    int sum=0;
    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;
            sum++;
        }
        if(sum==n-1)break;
    }
    return ans;
}
int main()
{

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

    }
    return 0;
}
kruskal

 

Guess you like

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