题目描述
某国有 �n 个城市,它们互相之间没有公路相通,因此交通十分不便。为解决这一“行路难”的问题,政府决定修建公路。修建公路的任务由各城市共同完成。
修建工程分若干轮完成。在每一轮中,每个城市选择一个与它最近的城市,申请修建通往该城市的公路。政府负责审批这些申请以决定是否同意修建。
政府审批的规则如下:
如果两个或以上城市申请修建同一条公路,则让它们共同修建;
如果三个或以上的城市申请修建的公路成环。如下图,A 申请修建公路 AB,B 申请修建公路 BC,C 申请修建公路 CA。则政府将否决其中最短的一条公路的修建申请;
其他情况的申请一律同意。
![](https://i-blog.csdnimg.cn/blog_migrate/cd56d708d0386a3f24ed0af67e229ab3.png)
一轮修建结束后,可能会有若干城市可以通过公路直接或间接相连。这些可以互相连通的城市即组成“城市联盟”。在下一轮修建中,每个“城市联盟”将被看作一个城市,发挥一个城市的作用。
当所有城市被组合成一个“城市联盟”时,修建工程也就完成了。
你的任务是根据城市的分布和前面讲到的规则,计算出将要修建的公路总长度。
![](https://i-blog.csdnimg.cn/blog_migrate/5826b884f470b50f5722915306e4c00b.png)
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
int n, m, k;
const int N = 5010;
double dis[N];//储存距离
double jud[N];
double ans;//储存答案//也就是公路总长
double now , minn;
struct ALL//储存坐标
{
double x, y;
}node[5010];
double check(double x1, double y1, double x2, double y2)//计算两点之间的距离
{
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}//dij是更新到起始点的距离,prim是更新到集合s的距离
void prim()
{
dis[1] = 0.0;//从第一号城市开始生成//即1号点在树上
jud[1] = 1;//已经遍历过的点(城市
int now;
double minn;
for (int i = 1; i <= n; i++)//每次循环选出一个点加入到生成树
{
now = 1;
minn = 0x3f3f3f3f;//先取最大值//方便后面判断
for (int j = 1; j <= n; j++)
{
if (!jud[j] && dis[j] < minn)//未被选择过并且到树的距离最短
{
now = j;
minn = dis[j]; //更新最小的那条边
}
}
jud[now] = 1;//选择该点
ans += dis[now];
for (int j = 1; j <= n; j++)//更新生成树外一点到生成树的距离
{
dis[j] = min(dis[j], check(node[now].x, node[now].y, node[j].x, node[j].y));
}
}
printf("%.2lf", ans);
}
void solve()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> node[i].x >> node[i].y;
dis[i] = 1e12;//先将距离都初始化为最大值,方便找到最小的
}
prim();
return;
}
int main()
{
//int T;
//cin >> T;
//while (T--)
//{
solve();
//}
return 0;
}