zoj 2048 Highways poj 1751

两题几乎就是一摸一样的,只是输入格式不一样。

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;
const int MAX = 1000;
const int INF = 10000010;

struct Point
{
    int x,y;
} point[MAX];

int dist[MAX],edge[MAX][MAX];
int n,m;

void Inite()
{
	int i, j;
	int a, b;
	cin>>n;
    for(i=1; i<=n; i++)
    {
        cin>>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] = (point[i].x - point[j].x) * (point[i].x - point[j].x) + (point[i].y - point[j].y) * (point[i].y - point[j].y);
        }
    }
    cin>>m;
    for(i=1; i<=m; i++)
    {
        cin>>a>>b;
        edge[a][b] = edge[b][a] = 0;
    }
}

void prim()
{
    int i,j,v;
	int index[MAX];
    for(i=1; i<=n; i++)
    {
        dist[i] = edge[1][i];
        index[i] = 1;
    }
    index[1] = -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)
            cout<<index[v]<<" "<<v<<endl;
            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;
	cin>>T;
    while(T--)
	{
		Inite();
		prim();
		if(T != 0)
			cout<<endl;
	}
    return 0;
}


你可能感兴趣的:(MST)