兩道初級樹形DP

來源:互聯網
上載者:User
/* * Anniversary_party.c * *  Created on: 2012-3-13 *      Author: timest */#define DEBUG#include <stdio.h>#include <stdlib.h>#define MAX 6001int max(int a, int b){return a > b? a : b;}enum bool{false,true};int n;int dp[MAX][2];int value[MAX];int p[MAX];void dfs(int root){int leaf = true;int dp0 = 0,dp1 = 0;for(int i = 1; i <= n; i++) {if(p[i] == root){//有孩子leaf = false;dfs(i);dp0 += max(dp[i][1], dp[i][0]);dp1 += dp[i][0];}}if(leaf == true){dp[root][0] = 0;dp[root][1] = value[root];}else{dp[root][0] = dp0;dp[root][1] = dp1 + value[root];}}int main(){#ifdef DEBUGfreopen("/tmp/in","r",stdin);#endifwhile(scanf("%d",&n)!=EOF){for(int i = 1; i <= n; i++) {scanf("%d",&value[i]);}for(int i = 1; i <= n; i++) {p[i] = -1;}int a,b;int sum = 0;while(scanf("%d%d",&a,&b),a,b){p[a] = b; //a的父節點是b}for(int i=1; i <= n; i++) {if(p[i]==-1){ // i節點沒有父親dfs(i);sum += max(dp[i][0], dp[i][1]);}}printf("%d\n",sum);}return 0;}

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1520

#define DEBUG#define true 1#define false 0#define bool int#include <stdio.h>#include <stdlib.h>#include <string.h>#include <memory.h>#define MAX 1500int p[MAX], n ;int dp[MAX][2];int min(int a, int b){return a  > b ? b : a;}void dfs(int root){bool leaf = true; //判斷是否為葉子節點int dp1 = 0, dp0 = 0;for(int i = 0; i < n; i++) {if(p[i] == root){leaf = false;dfs(i);dp1 += min(dp[i][0], dp[i][1]);dp0 += dp[i][1];}}//如果是葉子節點if(leaf) {dp[root][0] = 0;dp[root][1] = 1;}else {dp[root][0] = dp0;dp[root][1] = dp1 + 1;}}int main() {#ifdef DEBUGfreopen("/tmp/in", "r", stdin);#endifint t,m,s;while(scanf("%d",&n)!=EOF && n!=0) {for(int i=0; i < n; i++)p[i] = -1; //-1 表示 根節點for(int i=0; i < n; i++){scanf("%d:(%d)",&t,&m);for(int j = 0; j < m; j++){scanf("%d",&s);p[s] = t; //s節點的父節點是i}}for(int i = 0; i < n; i++) {if(p[i]==-1){dfs(i);printf("%d\n",min(dp[i][0],dp[i][1]));break;}}}return 0;}

題目連結:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1134

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.