Smooth Traffic Project adjourned - minimum spanning tree

Topic Link

Meaning of the questions:

Now decided to build a bridge, between a so-called eligible eligible island, is the distance between the islands is not less than 10 m, not greater than 1000 m. Of course, in order to save money, there are only required to achieve between any two roads lead to the island. Which bridge the price is 100 yuan / m.

answer:

Bare minimum spanning tree board

Calculated the distance between the two islands, ans updated when necessary to determine the distance between the two islands is between [10,1000]

Figure Unicom i.e. whether the last sum is equal to n-1 is output if not equal  OH!

Code:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 10005;
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[maxn];

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()
{
    double ans=0.0;
    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 && edge[i].w>=10 && edge[i].w<=1000)
        {
            f[fx]=fy;
            sum++;
            ans+=edge[i].w;
        }
        if(sum==n-1)break;
    }
    if(sum==n-1)printf("%.1f\n",ans*100);
    else printf ("oh!\n");
}
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);
    return dis;
}
int main ()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        cnt=0;
        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);
        }
        kruskal();
    }


    return 0;
}
kruskal

 

Guess you like

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