题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=203
题意:
将n个城市,全部连通起来的最短长度
分析:
n个点,每个点与其他n-1个点均可相连,距离d由坐标计算可得
两点距离为每条边的权值,直接Kruskal算了得到最小生成树结果
核心:
void Kruskal()
{
int ans = 0, num = 0;
for(i = 1; i<m; i++)
{
if(Find( x[i] ) != Find( y[i] ))
{
ans += w[i];
num++;
Union( x[i], y[i] );
}
if(num >= n-1) break;
}
printf("%d\n", ans);
}
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <math.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <vector>
using namespace std;
#define MAXN 110
#define MAXM 5010
#define MIN -1e+10
#define INF 0x7f7f7f7f
struct edge
{
int u, v;
double w;
bool operator < (const edge & e)const
{
return w < e.w;
}
}edges[MAXM];
int n, m, i, j;
double x[MAXN], y[MAXN];
double ans;
int parent[MAXN];
int Case;
int Find(int x)
{
int s, temp;
for(s = x; parent[s] >= 0; s = parent[s]);
while(s != x)
{
temp = parent[x];
parent[x] = s;
x = temp;
}
return s;
}
void Union(int x, int y)
{
int r1 = Find(x), r2 = Find(y);
int temp = parent[r1] + parent[r2];
if(parent[r1] > parent[r2])
{
parent[r1] = r2;
parent[r2] = temp;
}
else
{
parent[r2] = r1;
parent[r1] = temp;
}
}
void Kruskal()
{
memset(parent, -1, sizeof(parent));
ans = 0;
int num = 0;
int u, v;
for(i = 0; i<m; i++)
{
u = edges[i].u;
v = edges[i].v;
if(Find(u) != Find(v))
{
ans += edges[i].w; num++;
Union(u, v);
}
if(num >= n-1)
break;
}
if(Case>1)printf("\n");
printf("Case #%d:\n", Case++);
printf("The minimal distance is: %.2lf\n", ans);
}
int main()
{
//freopen("a.txt", "r", stdin);
Case = 1;
while(~scanf("%d", &n) && n)
{
for(i = 0; i<n; i++)
{
scanf("%lf%lf", &x[i], &y[i]);
}
double d;
m = 0;
for(i = 0; i<n; i++)
{
for(j = i+1; j<n; j++)
{
d = sqrt((x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j]));
edges[m].u = i;
edges[m].v = j;
edges[m].w = d;
m++;
}
}
sort(edges, edges + m);
Kruskal();
}
return 0;
}