POJ 1251 MST Krustral

1.Question:

題意:
題目中說明了是邊數不會超過75,可見是稀疏圖,我們直接Krustral 0MS水過
來測模板了

2.Solution:

本題唯一的難點在於理解題意,和圖的構建
沒什麼難的

3.Code:

#include"iostream"
#include"cstdio"
#include"cstring"
#include"algorithm"

using namespace std;

typedef struct node
{
	char atom;
	int x;
	int y;
	int weight;
}point;

point edge[100];
int n;
int edgenum=0;
int fa[10000];
int book[10000];

void init(int n)
{
	for(int i=0;i<n;i++) fa[i]=i;
}

int find(int x)
{
	if(fa[x]==x) return x;
	else return fa[x]=find(fa[x]);
}

void unit(int x,int y)
{
	x=find(x);
	y=find(y);
	if(x==y) return ;
	else fa[x]=y;
}

bool same(int x,int y)
{
	return find(x)==find(y);
}

bool cmp(point a,point b)
{
	if(a.weight>b.weight) return false;
	else return true;
}

int main()
{
	int ans=0;
	while(scanf("%d",&n)&&n)
	{
		edgenum=0;
		memset(edge,0,sizeof(edge));
		memset(book,0,sizeof(book));
		ans=0;
		getchar();
		for(int i=1;i<n;i++) 
		{
			int k;
			char p[10];
			scanf("%s%d",p,&k);
			for(int j=0;j<k;j++)
			{
				char save[10];
				int kk;
				scanf("%s%d",save,&kk);
				edgenum++;
				edge[edgenum].atom=p[0];
				edge[edgenum].x=p[0]-'A';
				edge[edgenum].y=save[0]-'A';
				edge[edgenum].weight=kk;
			}
		}
		sort(edge+1,edge+edgenum+1,cmp);
		init(n);
		int count=0;
		for(int i=1;i<=edgenum;i++)
		{
			if(!same(edge[i].x,edge[i].y))
			{
				count++;
				ans+=edge[i].weight;
				unit(edge[i].x,edge[i].y);
				if(count==n-1) break;
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章