4033: [Haoi2015]t1 time limit: ten Sec Memory Limit: + MB
Submit: 819 Solved: 375
[Submit] [Status] [Discuss] Description has a tree with a number of N points, and the tree edge has edge rights. Give you a positive integer k within 0~ N, you want to select K points in this tree, dye it black, and turn the other n-k Dianran into white. After all points are dyed, you will get the distance between the black dots 22 plus the white Point 22 distance and the benefit. Ask what the maximum benefit is. Input
The first line consists of two integers N, K.
Next N-1 line three positive integer fr, to, dis, indicating that there is an edge (fr, to) in the tree with a length of dis. Enter to ensure that all points are connected to each other. Output
Outputs a positive integer that represents the maximum value of the benefit.
Sample Input3 1
1 2 1
1 3 2Sample Output3HINT
For 100% of data, 0<=k<=n <=2000
Source
Acknowledgement BHIAIBOGF offers
[Submit] [Status] [Discuss] Puzzle : Tree-shaped DP
F[I][J] Indicates the maximum benefit value of the J Black Point selected from the subtree of I.
For an edge C[i], his contribution is (the number of black dots in his subtree x the number of black dots outside the subtree + the number of white points in the subtree x the number of white dots outside the subtree) xc[i], because it is the black point and white point between the 22 of the edge, to reach the subtrees tree, then it must go through this edge, so this edge is passed by the
So what if it shifts?
F[x][j]=max (F[x][j],f[x][j-l]+f[v[i]][l] (contribution of the current subtree) + contribution of the current side)
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include < Cmath> #define LL Long longusing namespace std; LL f[2003][2003];int tot,next[4003],point[4003],size[2003],v[4003],c[4003];int n,k;void Add (int x,int y,int z) {tot++; NEXT[TOT]=POINT[X]; Point[x]=tot; V[tot]=y; c[tot]=z;tot++; Next[tot]=point[y]; Point[y]=tot; V[tot]=x; C[tot]=z;} void Dfs (int x,int fa) {f[x][0]=f[x][1]=0;size[x]=1;for (int i=point[x];i;i=next[i]) if (V[I]!=FA) {DFS (v[i],x); Size[x] +=size[v[i]]; for (int j=min (k,size[x]), j>=0;j--) for (int l=0;l<=min (J,size[v[i]]), l++) {ll ans1= (LL) (l* (K-L)) *c[i]; ll Ans2= (LL) (size[v[i]]-l) * (n-k-(size[v[i]]-l)) *c[i]; F[x][j]=max (F[X][J],F[X][J-L]+F[V[I]][L]+ANS1+ANS2); }}}int Main () {scanf ("%d%d", &n,&k), memset (F,128,sizeof (f)), for (int i=1;i<n;i++) {int x, Y, scanf ("%d%d%d ", &x,&y,&z); Add (x, y, z); }dfs (1,0);p rintf ("%lld\n", F[1][k]);}
Bzoj 4033: [Haoi2015]t1 (tree DP)