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

我也会树形dp了

Posted by phython at 2017-03-12 11:04:00 on Problem 2057
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX = 1111;
int N;
vector<int> G[MAX];
char c[MAX];
int dp[MAX];//表示当壳在该子树下面时,遍历完所需要步骤数
int leaf[MAX];//表示某节点下有多少叶子
int fail[MAX];//表示壳不在子树下面,遍历完再回来需要步骤数 
bool cmp(int a,int b)
{
	return (2+fail[a])*leaf[b] < (2+fail[b])*leaf[a];
}
void dfs(int u)
{
	int flag = 0;
	for(int i = 0;i < G[u].size();++i)
	{
		int v = G[u][i];
		dfs(v);
		flag = 1;
		leaf[u] += leaf[v];
	}
	sort(G[u].begin(),G[u].end(),cmp);
	if(!flag) leaf[u] = 1;
	for(int i = 0;i < G[u].size();++i)
	{
		int v = G[u][i];
		dp[u] += fail[u]*leaf[v] + dp[v] + leaf[v];
		fail[u] += fail[v] + 2;
	}
	if(c[u] == 'Y') fail[u] = 0;
}
int main()
{
	while(~scanf("%d",&N)&&N)
	{
		memset(dp,0,sizeof(dp));
		memset(leaf,0,sizeof(leaf));
		memset(fail,0,sizeof(fail));
		for(int i = 1;i <= N;i++) G[i].clear();
		for(int i = 1;i <= N;i++)
		{
			int fa;
			scanf("%d %c",&fa,&c[i]);
			if(fa == -1) continue;	
			G[fa].push_back(i);	
		}
		dfs(1);
		printf("%.4f\n",double(dp[1])/double(leaf[1]));	
	}
	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