大意:让你用最小的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;
}

 

posted on 2012-10-25 15:58  有间博客  阅读(193)  评论(0编辑  收藏  举报