• POJ 1694 古老的游戏 | 贪心 | 树形DP


    Description

      有一个古老的石头游戏,该游戏基于任意一棵树T,游戏的目标是在树T的根节点上放一颗石头,游戏的规则如下:

      1、 游戏开始前,玩家先将K个石头放入桶中。
      2、 在游戏的每一步,玩家从桶中拿一颗石头放到树的一个空的叶子节点上。
      3、 当一个节点p的所有r个子节点都有一个石头,则移去r个子节点上的石头,然后将一个石头放到节点p上。剩下的r-1个石头重新放到桶中重复使用。

      如果玩家根据以上规则放置石头,并最终在根节点上放置一颗石头,则赢得游戏。现在的任务是求出游戏开始时,石头数K的最小值,使得玩家能在给定树的情况下赢得游戏。

    Input

      第一行输入测试用例的个数T,每个测试用例是一颗树的描述。第二行开始输入每棵树的描述。  每棵树有N个节点,节点标号为1,2,...N,每个节点可以有任意个子节点,根节点标号为1。树的描述第一行为节点数N,第二行开始按照节点标号顺序描述N个节点的子节点,每行第一个数为标号p,第二个数为子节点数r,如果r不为0,接下来为r个子节点的标号。

    Output

      对每棵树,输出石头数的最小值。

    Sample Input 1

    2
    7
    1 2 2 3
    2 2 5 4
    3 2 6 7
    4 0
    5 0
    6 0
    7 0
    12
    1 3 2 3 4
    2 0
    3 2 5 6
    4 3 7 8 9
    5 3 10 11 12
    6 0
    7 0
    8 0
    9 0
    10 0
    11 0
    12 0

    Sample Output 1

    3
    4

    Hint

    1<=T<=100,1<=N<=1000


    贪心思路,从子节点需求最大的一个开始看,每个子节点最多可以剩余需求量-1个石头,如果之前剩余的石头不够当前子节点的需求就补齐至需求的数量。

    #include <cstdio>
    #include <iostream>
    #include <cmath>
    #include <cstring>
    #include<algorithm>
    #include<vector>
    #define inf 0x3f3f3f3f
    #define maxn 1005
    #define maxm 1005
    #define mo 3153600
    #define _for(i,a,b) for(int i=(a);i<(b);++i)
    #define _rof(i,a,b) for(int i=(a);i>(b);--i)
    #define _rep(i,a,b) for(int i=(a);i<=(b);++i)
    #define _per(i,a,b) for(int i=(a);i>=(b);--i)
    using namespace std;
    typedef unsigned long long ULL;
    typedef long long ll;
    int fir[maxn],ne[maxm],to[maxm],np=0;
    void add(int x,int y){
    	ne[++np]=fir[x];
    	fir[x]=np;
    	to[np]=y;
    }
    int dp[maxn];
    void dfs(int u){
    	if(!fir[u]){
    		dp[u]=1;
    		return;
    	}
    	int cnt=0,tmp[maxn];
    	for(int i=fir[u];i;i=ne[i]){
    		int v=to[i];
    		dfs(v);
    		tmp[++cnt]=dp[v];
    	}
    	sort(tmp+1,tmp+1+cnt,greater<int>());
    	dp[u]=0;
    	for(int i=1,re=0;i<=cnt;i++,re--){
    		if(tmp[i]>re){
    			dp[u]+=(tmp[i]-re);
    			re=tmp[i];
    		}
    	}
    	return;
    }
    int n;
    void init(){
    	memset(fir,0,sizeof fir);
    	np=0;
    	scanf("%d",&n);
    	_rep(i,1,n){
    		int x,y,k;
    		scanf("%d%d",&x,&k);
    		while(k--){
    			scanf("%d",&y);
    			add(x,y);
    		}
    	}
    }
    int main(){
    	int t;
    	scanf("%d",&t);
    	while(t--){
    		init();
    		dfs(1);
    		printf("%d
    ",dp[1]);
    	}
    	return 0; 
    }
    
  • 相关阅读:
    HTML标签(二)
    HTML 表单
    HTML列表
    HTML表格
    Critical Section Problems
    Stack, Queue and Priority Queue
    Introduction to Dynamic Set
    Introduction to Divide-and-Conquer
    Sorting Algorithms Overview
    Python学习笔记(三)数据类型
  • 原文地址:https://www.cnblogs.com/de-compass/p/11248252.html
Copyright © 2020-2023  润新知