POJ3342 HDU2412 Party at Hali-Bula

60 篇文章 0 订阅
48 篇文章 0 订阅

同上一题一样,树形DP经典题

这里的结构体内我们加多两个变量,表示idx节点出现与否时,以它为根的树的最优值是否唯一

而这两个变量的的更新可以看代码中的dfs


/*******************************************************************************
 # Author : Neo Fung
 # Email : neosfung@gmail.com
 # Last modified: 2012-04-26 20:27
 # Filename: POJ3342 HDU2412 Party at Hali-Bula.cpp
 # Description : 
 ******************************************************************************/
#ifdef _MSC_VER
#define DEBUG
#define _CRT_SECURE_NO_DEPRECATE
#endif

#include <fstream>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include <limits.h>
#include <algorithm>
#include <math.h>
#include <numeric>
#include <functional>
#include <ctype.h>
#include <map>
#define MAX 100010
using namespace std;

struct NODE
{
  int child,father,brother,present,not_present;
  bool present_unique,not_present_unique;
  void init()
  {
    child=father=brother=not_present=0;
    present=present_unique=not_present_unique=1;
  }
  int max()
  {
    return present>not_present?present:not_present; 
  }
}node[MAX];

void dfs(const int &idx)
{
	int child=node[idx].child;
	while(child)
	{
		dfs(child);
		node[idx].present+=node[child].not_present;
		node[idx].not_present+=node[child].max();
    if(!node[child].not_present_unique)
      node[idx].present_unique=false; //本节点出现,则本节点的最优值是否唯一只和子节点不出现的最优值是否唯一有关
    if(node[child].present==node[child].not_present)
      node[idx].not_present_unique=false;//本节点不出现,则本节点的最优值是否唯一只和子节点出现与否时的值是否相等有关
		child=node[child].brother;
	}
}

int main(void)
{
#ifdef DEBUG  
  freopen("../stdin.txt","r",stdin);
  freopen("../stdout.txt","w",stdout); 
#endif  

  int n;
	map<string,int>::iterator iter;
	string son,father;

  while(~scanf("%d",&n) && n)
  {
		map<string,int> sn_map;
		cin>>father;
		sn_map[father]=1;
		node[1].init();
		int cnt=2;
		for(int i=1;i<n;++i)
		{
			cin>>son>>father;
			iter=sn_map.find(son);
			if(iter==sn_map.end())
      {
        node[cnt].init();
				sn_map[son]=cnt++;
      }
			iter=sn_map.find(father);
			if(iter==sn_map.end())
      {
        node[cnt].init();
				sn_map[father]=cnt++;
      }
			int n_child=sn_map[son],n_father=sn_map[father];
			node[n_child].father=n_father;
			node[n_child].brother=node[n_father].child;
			node[n_father].child=n_child;
		}
    dfs(1);
    int ans,flag;
    if(node[1].present==node[1].not_present)
      ans=node[1].present,flag=0;
    else if(node[1].present>node[1].not_present)
      ans=node[1].present,flag=node[1].present_unique;
    else
      ans=node[1].not_present,flag=node[1].not_present_unique;
    printf("%d %s\n",ans,flag?"Yes":"No");
  }

  return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值