BZOJ 2427 软件安装 树形dp+tarjan

来源:互联网 发布:乳液推荐 知乎 编辑:程序博客网 时间:2024/06/06 20:03

现在我们的手头有N个软件,对于一个软件i,它要占用Wi的磁盘空间,它的价值为Vi。我们希望从中选择一些软件安装到一台磁盘容量为M计算机上,使得这些软件的价值尽可能大(即Vi的和最大)。
但是现在有个问题:软件之间存在依赖关系,即软件i只有在安装了软件j(包括软件j的直接或间接依赖)的情况下才能正确工作(软件i依赖软件j)。幸运的是,一个软件最多依赖另外一个软件。如果一个软件不能正常工作,那么它能够发挥的作用为0。

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

显然建有向图之后图是一些环+树
考虑选择一个环,那么久必须将这个环全选才可以,否则都不能满足要求,因而我们可以用tarjan将他缩成一个点,这样的话就彻底是一棵树啦
然后我们在树上进行背包就行
但是要注意依赖关系的问题,我们可以先循环msumwx的部分,在做完了全部之后,再直接f(i,j)=f(i,jsumwx)+sumwv,这里的sum指的都是该强连通分完之后的块内信息
然后就结束啦

#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>#define N 1000+5#define M 5000+5using namespace std;int head[N],last[N];int n , m;int f[N][N];inline int read(){    int x=0,f=1;char ch = getchar();    while(ch < '0' || ch > '9'){if(ch == '-')f=-1;ch = getchar();}    while(ch >='0' && ch <='9'){x=(x<<1)+(x<<3)+ch-'0';ch = getchar();}    return x*f;}struct graph{    int next,to;    graph () {}    graph (int _next,int _to)    :next(_next),to(_to){}}edge[M],tmp[M];inline void addfir(int x,int y){    static int tt = 0;    tmp[++tt] = graph(last[x],y);    last[x] = tt;}bool vis[N];inline void addsec(int x,int y){    static int cnt = 0;vis[y] = 1;    edge[++cnt] = graph(head[x],y);    head[x] = cnt;}int scc;int stack[N],top,belong[N];int depth,dfn[N],low[N];int v[N],w[N],sv[N],sw[N];bool in[N];void tarjan(int x){    low[x] = dfn[x] = ++depth;    stack[++top] = x; in[x] = 1;    for(int i=last[x];i;i=tmp[i].next)        if(!dfn[tmp[i].to])            tarjan(tmp[i].to),low[x] = min(low[x],low[tmp[i].to]);        else if(in[tmp[i].to])             low[x] = min(low[x],dfn[tmp[i].to]);    int now = 0;    if(low[x] == dfn[x])    {        scc ++ ;        while(now ^ x)        {            now = stack[top --];            in[now] = 0;            belong[now] = scc;            sv[scc] += v[now],sw[scc] += w[now];        }    }    return;}void rebuild(){    for(int i=1;i<=n;++i)        for(int j=last[i];j;j=tmp[j].next)            if(belong[i]!=belong[tmp[j].to])                addsec(belong[i],belong[tmp[j].to]);}void DFS(int x){    for(int i=head[x];i;i=edge[i].next)    {        DFS(edge[i].to);        for(int j = m - sw[x] ; j>=0 ;--j)            for(int k = 0; k <= j ; ++k)                f[x][j] = max(f[x][j],f[x][k] + f[edge[i].to][j-k]);    }    for(int j = m ; j>=0 ; --j)        if(j >= sw[x])f[x][j] = f[x][j-sw[x]] + sv[x];        else f[x][j] = 0;}int main(){    n = read() , m = read();    for(int i=1;i<=n;++i)w[i] = read();    for(int i=1;i<=n;++i)v[i] = read();    for(int i=1;i<=n;++i){        int x = read();        if(x) addfir(x,i);    }     for(int i=1;i<=n;++i)        if(!dfn[i])            tarjan(i);    rebuild();    int root = scc + 1;    for(int i=1;i<=scc;++i)        if(!vis[i])addsec(root,i);    DFS(root);    cout<<f[root][m];}

0 0
原创粉丝点击