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 1083_3 at 2006-12-09 21:58:01 on Problem 3140
#include<stdio.h>
#include<vector>
#include<queue>
using namespace std;
struct Node
{
	__int64 value;
	bool ext;
	int parent;//记录父节点
	int son;//纪录儿子节点数目
	vector<int> next;
};
Node node[100001];
int temp[100001];
int N,M;
int TOTAL;
void input()
{
	int i,a,b;
	for( i = 1; i <= N; i++ )
	{
		scanf("%I64d",&node[i].value);
		TOTAL += node[i].value;
	}
	for( i = 1; i <= M; i++ )
	{
		scanf("%d %d",&a,&b);
		node[a].next.push_back(b);
		node[b].next.push_back(a);
	}
	queue<int> que;
	que.push(1);
	node[1].ext = true;
	while(que.size()>0)//广搜构建一棵树
	{
		int par = que.front();
		for( i = 0; i < node[par].next.size(); i++ )
		{
			
			int son = node[par].next[i];
			if ( node[son].ext == false )
			{
				node[son].ext = true;
				que.push(son);
				node[par].son++;
				node[son].parent = par;
			}
		}
		que.pop();
	}
}
__int64 run()
{
	int i,c;
	c = 0;
	int end = N;
	for( i = 1; i <= N; i++ )//找到所有叶子节点
	{
		if ( node[i].son == 0 )
			temp[c++] = i;
	}
	int newc = 0;
	end -= c;
	while(end)
	{
		for( i = 0; i < c; i++ )
		{
			int son = temp[i];
			int par = node[son].parent;
			node[par].value += node[son].value;//把每个叶子节点的值加到父节点
			node[par].son--;
			if ( node[par].son == 0 )//当所有儿子节点加完,该点变成叶子节点
				temp[newc++] = par;
		}
		c = newc;
		newc = 0;
		end -= c;
	}
	__int64 minD = TOTAL;
	for( i = 1; i <= N; i++ )
	{
		__int64 dif =  TOTAL - node[i].value;
		if ( dif > node[i].value )
			dif -= node[i].value;
		else
			dif = node[i].value - dif;
		if ( dif < minD )
			minD = dif;
	}
	return minD;
}
int main()
{
	int cas = 0,i;
	while(1)
	{
		cas++;
		scanf("%d %d",&N,&M);
		if ( N == 0 && M == 0 ) 
			break;
		TOTAL = 0;
		for( i = 0; i <= N; i++ )
		{
			node[i].son = 0;
			node[i].ext = false;
			node[i].next.clear();
		}
		input();
		__int64 re = run();;
		if ( N == 1 ) 
			re = node[1].value;	
		printf("Case %d: %I64d\n",cas,re);
	}
	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