20191111luogu1273 cable networks

luogu1273 cable networks

Meaning of the title:
the n-m-1 ~ + the n-points are for the user, there is no parent-child relationship between the user and the user's point, the rest of the points are not the user, the user has the right values
between the dots need to consume edge weights to build this one side, from the root to go through to reach the user side and get right to the point value of
the user requirements without a loss, and can reach a maximum of how much?

Backpack tree DP:
F [u] [j] u is represented by a root node j reaches the maximum profit of the user (profit may be negative, representing loss)
of transfers:
for the user to f [u] [1] = site weight of
the non-user point, initially f [u] [0] = 0 (f [u] [1] and others are -INF, because he himself is not a user point) of
the maximum value of its child j number (the number of note, but not the number of points the user points) included in the user tree points
f [u] [j] = max (f [u] [j], f [u] [j - k] + f [ too] [k] - val [ i]);
finally find that the f [1] [j] is greater than the maximum value of j is equal to 0 the
time complexity: O (nm ^ 2)

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 using namespace std;
 5 int to[6005],head[6005],nxt[6005],cnt,val[6005];
 6 int a[3005],siz[3005],f[3005][3005];
 7 int n,m;
 8 void add(int u,int v,int w)
 9 {
10     to[++cnt] = v;
11     nxt[cnt] = head[u];
12     head[u] = cnt;
13     val[cnt] = w;
14 }
15 void dfs(int u,int fa)
16 {
17     f[u][0] = 0;
18     if(u >= n - m + 1)
19     {
20         f[u][1] = a[u];
21         siz[u] = 1;
22     }
23     for(int i = head[u];i;i=nxt[i])
24     {
25         int too = to[i];
26         if(too == fa)continue;
27         dfs(too,u);
28         siz[u] += siz[too];
29         for(int j = siz[u];j >= 1;j --)
30         {
31             for(int k = 1;k <= min(j,siz[too]);k ++)
32             {
33                 f[u][j] = max(f[u][j],f[u][j - k] + f[too][k] - val[i]);
34                 
35 //            printf("f[%d][%d]==%d + f[%d][%d]==%d - %d = %d\n",u,j - k,f[u][j-k],too,k,f[too][k],val[i],f[u][j]);
36             }
37         }
38     }
39 }
40 int main()
41 {
42     scanf("%d%d",&n,&m);
43     for(int i = 1,k;i <= n - m;i ++)
44     {
45         scanf("%d",&k);
46         for(int j = 1,v,w;j <= k;j ++)
47         {
48             scanf("%d%d",&v,&w);
49             add(i,v,w);
50         }
51     }
52     for(int i = n - m + 1;i <= n;i ++)
53     {
54         scanf("%d",&a[i]);
55     }
56     memset(f,-0x3f,sizeof(f));
57     dfs(1,0);
58     for(int i = m;i >= 0;i --)
59     {
60 //        printf("f[1][%d]=%d\n",i,f[1][i]);
61         if(f[1][i] >= 0)
62         {
63             printf("%d",i);
64             break;
65         }
66     }
67     return 0;
68 }

 

Guess you like

Origin www.cnblogs.com/djfuuxjz/p/11833571.html