pku2485Highways(prim)

Xredman posted @ Mar 22, 2010 09:42:12 PM in Algorithm with tags pku MST prim , 1186 阅读

        MST之prim求解。

//6612475 Xredman 2485 Time Limit Exceeded   C++ 1131B 2010-03-23 08:21:16 
//超时源于写错了T 
//6612480 Xredman 2485 Accepted 560K 157MS C++ 1227B 2010-03-23 08:24:18 
//problem:http://acm.pku.edu.cn/JudgeOnline/problem?id=2485
#include <iostream>
#include <cstdio>
#include <climits>
using namespace std;

const int MAX_SIZE = 502;
const int INF = 0x7FFFFFFF;

int G[MAX_SIZE][MAX_SIZE];
int lowcost[MAX_SIZE],closeset[MAX_SIZE];

int n;//共有n个节点

void readin()
{
	int i, j;
	for(i = 0; i < n; i++)
	{
		for(j = 0; j < n; j++)
		{
			scanf("%d", &G[i][j]);
		}
	}
}

int prim(int v0)
{
	int i, j, k, minx;
	int res = -1;
	int sum = 0; 
	for(i = 0; i < n; i++)
	{//初始化辅助数组
		lowcost[i] = G[v0][i];
		closeset[i] = v0;
	}
	
	for(i = 1; i < n; i++)
	{
		//寻找离生成树最近的未加入顶点k
		minx = INF;
		for(j = 0; j < n; j++)
		{
			if(lowcost[j] < minx && lowcost[j] != 0)
			{
				minx = lowcost[j];
				k = j;
			}
		}
		//将顶点k加入生成树
		lowcost[k] = 0;
		if(minx > res)
			res = minx;
		sum += minx;
		/*
		*生成树中增加一条新边k到closeset[k],
		*修正各点的lowcost和closeset值
		*/
		for(j = 0; j < n; j++)
		{
			if(G[k][j] < lowcost[j])
			{
				lowcost[j] = G[k][j];
				closeset[j] = k;
			}
		}
	}
	cout<<sum<<endl;
	return res;
}

int main()
{
	int T;
	while(scanf("%d", &T) != EOF)
		while(T--)
		{
			scanf("%d", &n);
			readin();
			printf("%d\n", prim(0));
		}
	return 0;
}

 

 






NCERT 5th Class Syl 说:
Aug 31, 2023 08:47:37 PM

NCERT Class 5th new Syllabus 2024 is Recently Released by National Council of Educational Research and Training (NCERT) is an Autonomous Organisation set up in by the Government of India to Assist and Advise the Central and State Governments on Policies and Programmes for Qualitative Improvement in School Education,Students are Advised to Thoroughly go Through the NCERT Class Syllabus before they NCERT 5th Class Syllabus 2024 Start Studying for the new Session 2024.NCERT Class Syllabus 2024 Pdf Download.NCERT Class Examination Every Year Conducted Month of March, In this Web page you will get the Complete Syllabus of Accountancy.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter