Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

一个Prim算法引来的血案,大牛帮我一下,为什么测试数据都对了,可是总是WA

Posted by gfedcba at 2009-01-07 15:59:12 on Problem 1251 and last updated at 2009-01-07 16:03:04
#include <iostream>
using namespace std;

// 找出最小权集合中的最小权
int findMinEdge(int minCost[], int n)
{
	int i;
	int minIndex = 0;
	while (minCost[minIndex] == 0)
	{
		minIndex++;
	}
	for (i=minIndex+1; i<=n-1; i++)
	{
		if (minCost[i] < minCost[minIndex] && minCost[i] != 0)
		{
			minIndex = i;
		}
	}
	return minIndex;
}

int main()
{
	const bool VISIT = true;
	const bool UNVISIT = false;
	const int N = 27;
        int n;
	int i,j;
	int edges,cost;
	char a,b;
	int minCost[N] = {0}; // 当前MST到各未访问顶点的最小权
	int matrix[N][N] = {0};
	bool flag[N]; // 用来标记顶点是否被访问过
	
	int minSum ; 
	int minIndex;
	
	while (cin>>n && n!=0)
	{
		minSum = 0; 
		for (i=0; i<=n-1-1; i++)
		{
			cin>>a>>edges;
			for (j=0; j<=edges-1; j++)
			{
				cin>>b>>cost;
				matrix[a-'A'][b-'A'] = cost;
				matrix[b-'A'][a-'A'] = cost;			
			}
		}
		
		for (i=0; i<=n-1; i++)  // 第一次访问第一个顶点
		{
			minCost[i] = matrix[0][i];
			flag[i] = UNVISIT;
		}
		flag[0] = VISIT; 
		
		for (i=0; i<=n-1-1; i++)
		{
			minIndex = findMinEdge(minCost, n); // 访问权最小的顶点
			minSum += minCost[minIndex];
			minCost[minIndex] = 0;
			flag[minIndex] = VISIT;// 标志已经访问过
			
			for (j=0; j<=n-1; j++)  // 访问后,再一次处理minCost,求得当前MST到所有未访问的顶点最小权
			{
				if (matrix[minIndex][j] !=0)
				{
					if (matrix[minIndex][j]<minCost[j])
					{
						minCost[j] = matrix[minIndex][j];
					}
					else if (matrix[minIndex][j]>minCost[j] && flag[j]==UNVISIT && minCost[j]==0)
					{
						minCost[j] = matrix[minIndex][j];
					}
				}

				
			}
		}
		cout<<minSum<<endl;
		
	}
	
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator