Highways-- minimum spanning tree template title (seek distance)

Topic Link

Meaning of the questions:

A two-dimensional coordinate system, given the n coordinates of the vertices, the vertices between the m groups has a distance of 0, the minimum spanning tree output side of two coordinates of all distances is not 0

answer:

Bare minimum spanning tree board

It requires only the distance between any two points can be

 

Code:

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

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

void kruskal()
{
    int sum=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;
            sum++;
            if(edge[i].w>0)printf("%d %d\n",x,y);
        }
        if(sum==n-1)break;
    }
}
double get_dis(int i,int j)
{
    double dis=sqrt((x[i]-x[j])*(x[i]-x[j])*1.0+(y[i]-y[j])*(y[i]-y[j])*1.0);
    //printf("%.2f\n",dis);
    return dis;
}
int main()
{
    scanf("%d",&n);

    cnt=0;
    for(int i=0; i<=n; i++)f[i]=i;
    for(int i=1; i<=n; i++)scanf("%d%d",&x[i],&y[i]);
    for(int i=1; i<=n; i++)for(int j=i+1; j<=n; j++)
        {
            double dis=get_dis(i,j);
            add(i,j,dis);
        }
    scanf("%d",&m);
    while(m--)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        add(a,b,0);
    }
    kruskal();

    return 0;
}
kruskal

 

Guess you like

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