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

我的代码(有注释,适合新手,大牛们莫鄙视,谢谢……)

Posted by songzhenqi at 2010-07-23 21:23:47 on Problem 1251
#include <iostream>
using namespace std;


int prim(int n)
{
	int c[27][27];
	int i,j,u;
	
	int roadnum;    //邻接点的个数
	int sum=0;
	int T[100];     //最小花费生成树的边集(权)
    int w[100];      //顶点i近邻相关联边的权集
	int k;           //最小生成树中边的个数
	bool s[100];     //是否进入集合S
	int min;
/*---------图的初始化-----------*/
	for(i=0;i<n;i++)
		for(j=0;j<n;j++)
		{
			c[i][j]=1000000;
			//cout<<"c"<<"["<<i<<"]"<<"["<<j<<"]"<<c[i][j]<<endl;
		}
	for(i=0;i<n-1;i++)
	{
		char vn1;
		cin>>vn1;
		cin>>roadnum;
		if(roadnum==0)
			continue;
		else
		{   char vn2;
			for(j=0;j<roadnum;j++)
			{
				cin>>vn2;
				cin>>c[vn1-65][vn2-65];
				c[vn2-65][vn1-65]=c[vn1-65][vn2-65]; // 完整邻接二维数组
			}
		}
		c[vn1-65][vn1-65]=0;
	}

/*------------算法实现-----------------------------------------------*/
	s[0]=true;            //第一点放入集合S
	for(i=1;i<n;i++)      //初始化集合N
	{
		w[i]=c[0][i];     //顶点i到近邻边的权
		s[i]=false;       //将除第一点外的点均放入N集  
	}
	k=0;
	for(i=1;i<n;i++)      //执行n-1次搜索,将N中元素转移至S
	{
		u=0;
		min=100000;
		for(j=1;j<n;j++)
		{
			if(!s[j]&&w[j]<min)
			{
				u=j; min=w[j];
			}
		}
		if(u==0)  break;         
		T[k++]=w[u];            //记录近邻边的权重
		s[u]=true;              //将所搜索的点放入S中

/*-----------------------更新N中顶点的近邻信息---------------------------------*/
		for(j=1;j<n;j++)
			if(!s[j]&&c[u][j]<w[j])
				w[j]=c[u][j];
	}

	for(i=0;i<k;i++)
	{   //cout<<T[i]<<endl;
		sum=sum+T[i];
	}
//	cout<<T[0]<<" "<<T[1]<<" "<<T[2]<<" "<<T[3]<<endl;
//	cout<<c[0][8]<<" "<<c[6][4]<<"  "<<c[4][6]<<endl;
	return sum;



}

int main()
{   
	//freopen("in.txt","r",stdin);
	int n;
	while(cin>>n&&n!=0)
	{
		printf("%d\n",prim(n));
	}

	
	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