/*
最小生成树的题, 这个先撞将图,转换邻接矩阵, 再进行prim算法; 得到了到每个点的距离,
然后排序,按卫星的数量,把排序的最大几个排除了,就可以了;输出最后一个,即可;
*/
#include <iostream>
#include <fstream>
#include <cstring>
#include <math.h>
using namespace std;
const int INF = 1<<30;
double map[501][501];
double location[501][2];
int flag[501];
double temp[501];
//快速排序
int pritition(double *arr, int left, int right){
int i=left;
int j=right;
double k = arr[i];
while(i<j){
while(i<j && arr[j] >= k)
--j;
if(i<j) arr[i] = arr[j];
while(i<j && arr[i] <= k)
++i;
if(i<j) arr[j] = arr[i];
}
arr[i] = k;
return i;
}
void Qsort(double *arr, int left, int right){
int s;
if(left < right){
s = pritition(arr, left, right);
Qsort(arr, left, s-1);
Qsort(arr, s+1, right);
}
}
//prim算法
void prim(int n,int m){
memset(flag, 0, sizeof(flag));
memset(temp, 0, sizeof(temp));
int k,c=1,i,j;
double min;
for(i=1; i<=m; ++i){
temp[i] = map[1][i];
}
flag[1] = 1;
for(int i=1; i<=m; ++i){
min = INF;
for(int j=1; j<=m; ++j){
if(flag[j] != 1){
if(temp[j] < min){
min = temp[j];
k = j;
}
}
}
flag[k] = 1;
for(j=1; j<=m; ++j){
if(!flag[j] && temp[j] > map[k][j])
temp[j] = map[k][j];
}
}
Qsort(temp, 1, m);
printf("%.2lf\n", temp[m-n+1]);
}
//得到两个点的距离
double distance(double x,double y,double aimx,double aimy){
double nx = abs(aimx - x);
double ny = abs(aimy - y);
return sqrt((nx)*(nx) + ny*ny);
}
//初始化邻接矩阵
void init(int m){
for(int i=1; i<=m; ++i){
for(int j=1; j<=m; ++j){
if(i==j) map[i][j] = 0;
else map[i][j] = INF;
}
}
}
int main(){
//freopen("a.txt", "r", stdin);
//freopen("b.txt", "w", stdout);
int count,n,m,i,j,a,b;
scanf("%d",&count);
while(count--){
scanf("%d %d",&n,&m);
init(m);
for(i = 1; i <= m; ++i){
scanf("%lf%lf",&location[i][0],&location[i][1]);
}
//将图转成邻接矩阵
for(i = 1; i<=m; ++i){
for(j = i; j <= m; ++j){
double result = distance(location[i][0],location[i][1],location[j][0],location[j][1]);
map[j][i] = map[i][j] = result;
}
}
prim(n,m);
}
}
POJ 2349(prim + 贪心)
最新推荐文章于 2021-01-28 09:19:57 发布