[bzoj2427][HAOI2010]软件安装 Tarjan+树形DP

来源:互联网 发布:python爬虫书籍推荐 编辑:程序博客网 时间:2024/06/06 17:11

2427: [HAOI2010]软件安装

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 1239  Solved: 483
[Submit][Status][Discuss]

Description

现在我们的手头有N个软件,对于一个软件i,它要占用Wi的磁盘空间,它的价值为Vi。我们希望从中选择一些软件安装到一台磁盘容量为M计算机上,使得这些软件的价值尽可能大(即Vi的和最大)。

但是现在有个问题:软件之间存在依赖关系,即软件i只有在安装了软件j(包括软件j的直接或间接依赖)的情况下才能正确工作(软件i依赖软件j)。幸运的是,一个软件最多依赖另外一个软件。如果一个软件不能正常工作,那么它能够发挥的作用为0

我们现在知道了软件之间的依赖关系:软件i依赖软件Di。现在请你设计出一种方案,安装价值尽量大的软件。一个软件只能被安装一次,如果一个软件没有依赖则Di=0,这时只要这个软件安装了,它就能正常工作。

Input

1行:N, M0<=N<=100, 0<=M<=500
2行:W1, W2, ... Wi, ..., Wn 0<=Wi<=M
3行:V1, V2, ..., Vi, ..., Vn 0<=Vi<=1000
4行:D1, D2, ..., Di, ..., Dn0<=Di<=N, Di≠i

Output

一个整数,代表最大价值。

Sample Input

3 10
5 5 6
2 3 4
0 1 1

Sample Output

5

HINT

Source

Day2

 

树形DP入门题

#include<iostream>#include<cstring>#include<cstdio>using namespace std;const int N = 105;struct Edge{int to,next;}e[N*5],ee[N*5];int dfn[N],low[N],m,n;int id,scnt,vv[N],ww[N],cnt;int in[N],v[N],w[N],last[N],last2[N],f[N][N*5],q[N],top,belong[N];bool inq[N];void insert( int u, int v ){e[++cnt].to = v; e[cnt].next = last[u]; last[u] = cnt;}void insert2( int u, int v ){in[v] = 1; ee[++cnt].to = v; ee[cnt].next = last2[u]; last2[u] = cnt;}void tarjan( int x ){int now = 0;dfn[x] = low[x] = ++id;q[++top] = x; inq[x] = 1;for( int i = last[x]; i; i = e[i].next )if(!dfn[e[i].to]){tarjan(e[i].to);low[x] = min(low[x],low[e[i].to]);} else if( inq[e[i].to] ) low[x] = min(low[x],dfn[e[i].to]);if( low[x] == dfn[x] ){scnt++;while( now != x ){now = q[top--]; inq[now] = 0;belong[now] = scnt;vv[scnt] += v[now]; ww[scnt] += w[now];}}}void DP( int x ){for( int i = last2[x]; i; i = ee[i].next ){DP(ee[i].to);for( int j = m-ww[x]; j >= 0; j-- )for( int k = 0; k <= j; k++ )f[x][j] = max(f[x][j],f[x][k]+f[ee[i].to][j-k]);}for( int j = m; j >= 0; j-- ){if( j >= ww[x] ) f[x][j] = f[x][j-ww[x]]+vv[x];else f[x][j] = 0;}}void rebuild(){cnt = 0;for( int i = 1; i <= n; i++ )for( int j = last[i]; j; j = e[j].next )if( belong[e[j].to] != belong[i] )insert2(belong[i],belong[e[j].to]);}int main(){scanf("%d%d", &n, &m);for( int i = 1; i <= n; i++ ) scanf("%d", &w[i]);for( int i = 1; i <= n; i++ ) scanf("%d", &v[i]);for( int i = 1,x; i <= n; i++ ){ scanf("%d", &x); if( x ) insert(x,i); }for( int i = 1; i <= n; i++ ) if( !dfn[i] ) tarjan(i);rebuild();for( int i = 1; i <= scnt; i++ ) if( !in[i] ) insert2(scnt+1,i);DP(scnt+1);printf("%d", f[scnt+1][m]);return 0;}