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

color a tree (why my mathod is wrong?)

Posted by Washington at 2005-08-20 00:12:59 on Problem 2054
我的算法是每次找没有被入栈的ci最大的点,将他的没有入栈的父亲和父亲的父亲...依此入栈
然后从栈底开始求和,代码如下?这个贪心的方法不对?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct pi
{
	int c,id,sd;
}p[1010],t[1010];

int f[1010],pt[1010];
bool v[1010];

int cmp (const void *a,const void *b)
{
	int d= (((struct pi*)a)->c - ((struct pi *)b)->c);
	if (d>0) return 1;
	else if (d<0) return -1;
	int e=((struct pi *)a)->sd - ((struct pi *)b)->sd;
	if (e>0) return 1;
	else if (e<0) return -1;
	else return 0;
}

int main ()
{
	int n,r,fa,sn,i,tmp,ts,cnt,cn,sum;
	while (scanf ("%d%d",&n,&r) && (n || r))
	{
		memset (p,0,sizeof (p));
		memset (v,0,sizeof (v));
		memset (f,0,sizeof (f));
		memset (pt,0,sizeof (pt));

		for (i=1;i<=n;i++)
		{
			scanf ("%d",&p[i].c);
			p[i].id=i;
		}
		for (i=1;i<n;i++)
		{
			scanf ("%d%d",&fa,&sn);
			f[sn]=fa;
		}
		for (i=1;i<=n;i++)
		{
			cnt=0;
			tmp=i;
			while (tmp) 
			{
				cnt++;
				tmp=f[tmp];
			}
			p[i].sd=cnt;
		}
		memcpy (t,p,sizeof (p));
		qsort (&p[1],n,sizeof (p[0]),cmp);	
		cn=0;
		for (i=n;i>=1;i--)
		{
			tmp=p[i].id;
			if (v[tmp]==0)
			{
				cnt=cn;
				while (tmp>0)
				{
					if (v[tmp]==0) 
					{
						cnt++;
						tmp=f[tmp];
					}
					else break;
				}
				cn=cnt;
				tmp=p[i].id;
				while (tmp>0)
				{
					if (v[tmp]==0)
					{
						pt[cnt]=tmp;
						cnt--;
						v[tmp]=1;
						tmp=f[tmp];
					}
					else break;
				}
			}
		}
		sum=0;
		for (i=1;i<=n;i++)
			sum+=i*t[pt[i]].c;
		printf ("%d\n",sum);
	}
	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