Hdu 1875 畅通工程再续 程序参考

#include<iostream>

#include<cmath>

#include<vector>

using namespace std;

const int Max=1001;

vector <vector <double> > mat;

vector <double> dist;

vector <bool>  visited;

int n;

int minVertex()

{

    int next=-1;

	for (int i=0;i<n;i++)

	{

		if (visited[i]==false && (next==-1 || dist[i]<dist[next]))

		{

			next = i;

		}

	}

    return next;

}

double Prim()

{

	dist=mat[0];

	fill(visited.begin(),visited.end(),false);

    visited[0]=true; 

	double cost=0;

	int i;

	bool flag=true;

	for(i=1;i<n;i++)

	{

        int next=minVertex();

		visited[next]=true;

		if (dist[next]==Max) //不连通
		{

			flag=false;

			break;

		}

        cost+=dist[next];

        for (int j=0;j<n;j++)

		{

			if (visited[j]==false && mat[next][j]<dist[j]) 

			{

				dist[j]=mat[next][j];

			}

		}

    }

	if (flag==false)

		return -1;

	else

		return cost;

}

struct Position

{

	int x,y;

};

vector <Position> islands;

double dist2Pos(Position a,Position b)

{

	return sqrt((double)((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)));

}

void run()

{

	scanf("%d",&n);

	islands.resize(n);

	int i;

	for(i=0;i<n;i++) scanf("%d %d",&islands[i].x,&islands[i].y);

	mat.resize(n);

	visited.resize(n); 

	for(i=0; i<n; i++)

    {

		mat[i].resize(n);

		fill(mat[i].begin(),mat[i].end(),Max);

		mat[i][i]=0;

	}

	for(i=0; i<n; i++)

	{

        for(int j=0;j<n;j++)

        {

			double d=dist2Pos(islands[i],islands[j]);

			if (d>=10 && d<=1000)

			{

				mat[i][j]=d;

				mat[j][i]=d;

			}

        }

	}

    double cost=Prim();

	if (cost!=-1)

		printf("%.1lf/n",cost*100);

	else

		printf("oh!/n");

}

int main()

{

	int total;

	scanf("%d",&total);

	for(int now=1; now<=total; now++) run();

	return 0;

}
阅读更多

没有更多推荐了,返回首页