Poj 1751 Highways(prim)

题意:求最小生成树,给出了每个城市的坐标,和已经修建好的公路,求出除已经修建好的路的最小生成树的路径。  special judge~~~~~~

虽然是个模版题,但改了很久才A的,主要是一开始 不予考虑给出的公路。酿成大错......关键还是对prim不理解.........慢慢来吧。

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <climits>//形如INT_MAX一类的
#define MAX 1000
#define INF 0x7FFFFFFF
# define eps 1e-5
using namespace std;
struct Point
{
    int x,y;
} point[MAX];

int dist[MAX],edge[MAX][MAX];
int index[MAX],n,m;//index记录路径

int distance(int x1,int y1,int x2,int y2)//给出的坐标算距离
{
    return ((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}

void prim(int u)//prim模版
{
    int i,j,v;

    for(i=1; i<=n; i++)
    {
        dist[i] = edge[u][i];
        index[i] = u;
    }
    index[u] = -1;
    for(j=1; j<n; j++)
    {
        int min = INF;
        v = -1;
        for(i=1; i<=n; i++)
        {
            if(index[i] != -1 && min > dist[i])
            {
                min = dist[i];
                v = i;
            }
        }
        if(v != -1)
        {
            if(min != 0)//考虑已经给出的公路,所以给出的公路不输出
            printf("%d %d\n",index[v],v);
            index[v] = -1;
            for(i=1; i<=n; i++)//更新值
            {
                if(index[i] != -1 && edge[v][i] < dist[i])
                {
                    dist[i] = edge[v][i];
                    index[i] = v;
                }
            }
        }
    }
}
int main()
{
    int t,i,j,a,b;
    scanf("%d",&n);
    for(i=1; i<=n; i++)
    {
        scanf("%d%d",&point[i].x,&point[i].y);
    }
    for(i=1; i<=n; i++)
    {
        edge[i][i] = 0;
    }
    for(i=1; i<=n; i++)//构图
    {
        for(j=1; j<=n; j++)
        {
            if(i != j)
            edge[i][j] = distance(point[i].x,point[i].y,point[j].x,point[j].y);
        }
    }
    scanf("%d",&m);
    for(i=1; i<=m; i++)
    {
        scanf("%d%d",&a,&b);
        edge[a][b] = edge[b][a] = 0;//给出的公路归零
    }
    prim(1);
    return 0;
}


你可能感兴趣的:(Poj 1751 Highways(prim))