题面
https://www.luogu.org/problem/P3973
题解
花个图理解一下,就是要选$b[x][y])$,必须选$c[x]$和$c[y]$。
最大权闭即可。
#include<cstdio> #include<cstring> #include<iostream> #include<queue> #include<vector> #include<map> #include<utility> #define ri register int #define N 400050 #define INF 1000000007 #define S 0 #define T (n*n+1) using namespace std; int n,x; struct graph { vector<int> ed[N]; vector<int> w,to; int d[N],cur[N]; void add_edge(int u,int v,int tw) { to.push_back(v); w.push_back(tw); ed[u].push_back(to.size()-1); to.push_back(u); w.push_back(0) ; ed[v].push_back(to.size()-1); } bool bfs() { queue<int> q; memset(d,0x3f,sizeof(d)); d[S]=0; q.push(S); while (!q.empty()) { int x=q.front(); q.pop(); for (ri i=0;i<ed[x].size();i++) { int e=ed[x][i]; if (d[x]+1<d[to[e]] && w[e]) { d[to[e]]=d[x]+1; q.push(to[e]); } } } return d[T]<INF; } int dfs(int x,int limit) { if (x==T || limit==0) return limit; int sum=0; for (ri &i=cur[x];i<ed[x].size();i++) { int e=ed[x][i]; if (w[e] && d[x]+1==d[to[e]]) { int f=dfs(to[e],min(limit,w[e])); if (!f) continue; sum+=f; limit-=f; w[e]-=f; w[1^e]+=f; if (!limit) return sum; } } return sum; } int dinic() { int ret=0; while (bfs()) { memset(cur,0,sizeof(cur)); ret+=dfs(S,INF); } return ret; } } G; int main(){ cin>>n; int sum=0; for (ri i=1;i<=n;i++) for (ri j=1;j<=n;j++) { cin>>x; sum+=x; G.add_edge(i,i*n+j,INF); G.add_edge(j,i*n+j,INF); G.add_edge(i*n+j,T,x); } for (ri i=1;i<=n;i++) { cin>>x; G.add_edge(S,i,x); } cout<<sum-G.dinic()<<endl; }