51nod

分析

考虑钦定一个点一定在选出的子集中。

我们把钦定的这个点作为根,那么如果 $x$ 在子集中,则 $x$ 在两棵树上的父节点都应该在子集中。

那么问题就转化成了最大权闭合子图,直接网络流即可。

代码

// ===================================
//   author: M_sea
//   website: http://m-sea-blog.com/
// ===================================
#include <bits/stdc++.h>
#define re register
using namespace std;

inline int read() {
    int X=0,w=1; char c=getchar();
    while (c<'0'||c>'9') { if (c=='-') w=-1; c=getchar(); }
    while (c>='0'&&c<='9') X=X*10+c-'0',c=getchar();
    return X*w;
}

const int N=50+10;
const int V=50+10,E=2000+10;
const int inf=0x3f3f3f3f;

int n,w[N],ans=0;

struct Graph {
    struct edge { int v,nxt; } e[N<<1];
    int head[N],ecnt;
    Graph() { ecnt=0; }
    inline void addEdge(int u,int v) {
        e[++ecnt]=(edge){v,head[u]},head[u]=ecnt;
    }
} A,B;

int fa1[N],fa2[N];
inline void dfs1(int u,int f) {
    fa1[u]=f;
    for (re int i=A.head[u];i;i=A.e[i].nxt)
        if (A.e[i].v!=f) dfs1(A.e[i].v,u);
}
inline void dfs2(int u,int f) {
    fa2[u]=f;
    for (re int i=B.head[u];i;i=B.e[i].nxt)
        if (B.e[i].v!=f) dfs2(B.e[i].v,u);
}

struct edge { int v,w,nxt; } e[E<<1];
int head[V],ecnt;
inline void addEdge(int u,int v,int w) {
    e[++ecnt]=(edge){v,w,head[u]},head[u]=ecnt;
    e[++ecnt]=(edge){u,0,head[v]},head[v]=ecnt;
}

int lv[V],s,t;
inline int bfs() {
    memset(lv,0,sizeof(lv)); lv[s]=1;
    queue<int> Q; Q.push(s);
    while (!Q.empty()) {
        int u=Q.front(); Q.pop();
        for (re int i=head[u];i;i=e[i].nxt) {
            int v=e[i].v,w=e[i].w;
            if (w&&!lv[v]) lv[v]=lv[u]+1,Q.push(v);
        }
    }
    return lv[t]!=0;
}
inline int dfs(int u,int cpflow) {
    if (u==t||!cpflow) return cpflow;
    int addflow=0;
    for (re int i=head[u];i;i=e[i].nxt) {
        int v=e[i].v,w=e[i].w;
        if (w&&lv[v]==lv[u]+1) {
            int tmpadd=dfs(v,min(cpflow,w));
            addflow+=tmpadd,cpflow-=tmpadd;
            e[i].w-=tmpadd,e[i^1].w+=tmpadd;
        }
        if (!cpflow) break;
    }
    if (!addflow) lv[u]=0;
    return addflow;
}
inline int dinic() { int maxflow=0;
    for (;bfs();maxflow+=dfs(s,2e9));
    return maxflow;
}

inline void solve(int rt) {
    memset(head,0,sizeof(head)),ecnt=1; s=0,t=n+1;
    dfs1(rt,0),dfs2(rt,0); int sum=0;
    for (re int i=1;i<=n;++i) {
        if (w[i]>0) sum+=w[i],addEdge(s,i,w[i]);
        else addEdge(i,t,-w[i]);
    }
    for (re int i=1;i<=n;++i)
        if (i!=rt) addEdge(i,fa1[i],inf),addEdge(i,fa2[i],inf);
    ans=max(ans,sum-dinic());
}

int main() {
    n=read();
    for (re int i=1;i<=n;++i) w[i]=read();
    for (re int i=1;i<n;++i) {
        int u=read()+1,v=read()+1;
        A.addEdge(u,v),A.addEdge(v,u);
    }
    for (re int i=1;i<n;++i) {
        int u=read()+1,v=read()+1;
        B.addEdge(u,v),B.addEdge(v,u);
    }
    for (re int i=1;i<=n;++i) solve(i);
    printf("%d\n",ans);
    return 0;
}
最后修改:2020 年 03 月 14 日 05 : 36 PM