大意:使用最小连线使得所有给定的点连在一起。
思路:最小生成树。
CODE:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
#define MAXN 110
#define INF 0X3F3F3F3F
struct node
{
double x, y;
}a[MAXN];
double w[MAXN][MAXN], d[MAXN];
int n;
double dist(node a, node b)
{
return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
}
double Prim(int src)
{
bool vis[MAXN] = {0};
double cnt = 0;
for(int i = 1; i <= n; i++) d[i] = (i == src)?0:INF;
for(int i = 1; i <= n; i++)
{
int x;
double m = INF;
for(int y = 1; y <= n; y++) if(d[y] < m && !vis[y]) m = d[x=y];
vis[x] = 1;
cnt += m;
for(int y = 1; y <= n; y++) d[y] = min(d[y], w[x][y]);
}
return cnt;
}
void init()
{
memset(w, INF, sizeof(INF));
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
init();
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
scanf("%lf%lf", &a[i].x, &a[i].y);
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(i == j) continue;
w[i][j] = dist(a[i], a[j]);
}
}
double ans = Prim(1);
printf("%.2lf\n", ans);
if(T) printf("\n");
}
return 0;
}
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
#define MAXN 110
#define INF 0X3F3F3F3F
struct node
{
double x, y;
}a[MAXN];
double w[MAXN][MAXN], d[MAXN];
int n;
double dist(node a, node b)
{
return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
}
double Prim(int src)
{
bool vis[MAXN] = {0};
double cnt = 0;
for(int i = 1; i <= n; i++) d[i] = (i == src)?0:INF;
for(int i = 1; i <= n; i++)
{
int x;
double m = INF;
for(int y = 1; y <= n; y++) if(d[y] < m && !vis[y]) m = d[x=y];
vis[x] = 1;
cnt += m;
for(int y = 1; y <= n; y++) d[y] = min(d[y], w[x][y]);
}
return cnt;
}
void init()
{
memset(w, INF, sizeof(INF));
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
init();
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
scanf("%lf%lf", &a[i].x, &a[i].y);
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(i == j) continue;
w[i][j] = dist(a[i], a[j]);
}
}
double ans = Prim(1);
printf("%.2lf\n", ans);
if(T) printf("\n");
}
return 0;
}