您的位置:首页 > 其它

UVA 10397 Connect the Campus

2012-10-25 15:58 253 查看
大意:让你用最小的cost连接所有的城市,有些城市已经连接好啦。

思路:最小生成树,连接好了的道路w[u][v] = w[v][u]赋值为0.

CODE:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <queue>
using namespace std;

#define MAXN 1100
#define INF 0X3F3F3F3F

int n, m;

struct node
{
double x, y;
}a[MAXN];

double w[MAXN][MAXN], d[MAXN];

void init()
{
memset(w, INF, sizeof(w));
}

double dist(const node a, const 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(!vis[y] && d[y] < m) 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;
}

int main()
{
while(~scanf("%d", &n))
{
init();
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)
{
w[i][j] = w[j][i] = dist(a[i], a[j]);
}
}
scanf("%d", &m);
while(m--)
{
int u, v;
scanf("%d%d", &u, &v);
w[u][v] = w[v][u] = 0;
}
double ans = Prim(1);
printf("%.2lf\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: