ZOJ 3201 Tree of Tree (树形DP)

Posted dwtfukgv

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ZOJ 3201 Tree of Tree (树形DP)相关的知识,希望对你有一定的参考价值。

题意:给定一棵树,求大小为k的一个子树的最大权值。

析:dp[i][j] 表示以 i 为根大小为 j 时最大权值。dp[i][j] = max{dp[i][j-k] + dp[son][k]},状态方程。

有一个要注意,因为要选的是一棵子树,所以以哪个点为根都行,也就是说,对于任意子树都能找一个合适的根,使得不会出现父结点与子结点冲突。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e16;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int maxn = 100 + 10;
const int mod = 1e9 + 7;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
  return r > 0 && r <= n && c > 0 && c <= m;
}

int dp[maxn][maxn];
int val[maxn];
struct Edge{
  int to, next;
};
int head[maxn], cnt;
Edge edge[maxn<<1];

void add_edge(int u, int v){
  edge[cnt].to = v;
  edge[cnt].next = head[u];
  head[u] = cnt++;
}
int ans;

void dfs(int u, int fa){
  dp[u][1] = val[u];
  for(int i = head[u]; ~i; i = edge[i].next){
    int v = edge[i].to;
    if(v == fa)  continue;
    dfs(v, u);
    for(int j = m; j > 1; --j)
      for(int k = 1; k < j; ++k)
        dp[u][j] = max(dp[u][j], dp[u][j-k] + dp[v][k]);
  }
  ans = max(ans, dp[u][m]);
}

int main(){
  while(scanf("%d %d", &n, &m) == 2){
    for(int i = 0; i < n; ++i)  scanf("%d", val+i);
    memset(head, -1, sizeof head);
    cnt = 0;
    for(int i = 1; i < n; ++i){
      int u, v;
      scanf("%d %d", &u, &v);
      add_edge(u, v);
      add_edge(v, u);
    }
    memset(dp, 0, sizeof dp);
    ans = 0;
    dfs(0, -1);
    printf("%d\n", ans);
  }
  return 0;
}

  

以上是关于ZOJ 3201 Tree of Tree (树形DP)的主要内容,如果未能解决你的问题,请参考以下文章

ZOJ3201(树形DP)

leetcode834 Sum of Distances in Tree

HDU 4863 Centroid of a Tree

Code the Tree ZOJ - 1097

ZOJ red black tree

ZOJ 3686 A Simple Tree Problem(线段树)