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

第一次用kruskal,帮忙看下为啥WA,多谢大牛!

Posted by love_mely at 2012-12-27 10:45:44 on Problem 1258 and last updated at 2012-12-27 10:54:08
#include<iostream>
using namespace std;
const int inf=100001;
int parent[110];
int graph[110][110];
int n;
int find(int k)
{
	return parent[k];
}
void unions(int i,int j)
{
	for(int k=0;k<n;k++)
		if(parent[k]==j)
			parent[k]=i;
}
int kruskal()
{
	/*initial*/
	bool visited[110][110];
	for(int i=0;i<110;i++)
	{
		parent[i]=i;
		for(int j=0;j<110;j++)
			visited[i][j]=false;
	}
		
	/*kruskal*/
	long int sum=0;
	int k=0;
	while(k < n-1)
	{
		int shortest=inf;
		int iIndex,jIndex;
		iIndex=jIndex=-1;
		for(int i=0;i<n;i++)
			for(int j=0;j<n;j++)
				if(i!=j && !visited[i][j] && graph[i][j]<shortest)
				{
					shortest=graph[i][j];
					visited[i][j]=true;
					visited[j][i]=true;
					iIndex=i;
					jIndex=j;
				}
		if(find(iIndex)!=find(jIndex))
		{
			unions(iIndex,jIndex);
			sum+=graph[iIndex][jIndex];
			k++;
		}
	}
	return sum;
}
int main(void)
{
	while(cin>>n)
	{
		for(int i=0;i<110;i++)
			for(int j=0;j<110;j++)
			{
				if(i==j)
					graph[i][j]=0;
				else 
					graph[i][j]=inf;
			}
		for(int i=0;i<n;i++)
			for(int j=0;j<n;j++)
				cin>>graph[i][j];
		cout<<kruskal()<<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