先推公式,推出个这,然后因为是 (0/1) 矩阵,选一个有损耗,两个一组有加成,就想到了最大权闭合子图,(飞行计划问题)
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, uu, ss, tt, hea[250505], cnt, cur[250505], maxFlow, lev[250505], ans;
const int oo=0x3f3f3f3f;
queue<int> d;
struct Edge{
int too, nxt, val;
}edge[1600005];
void add_edge(int fro, int too, int val){
edge[cnt].nxt = hea[fro];
edge[cnt].too = too;
edge[cnt].val = val;
hea[fro] = cnt++;
}
void addEdge(int fro, int too, int val){
add_edge(fro, too, val);
add_edge(too, fro, 0);
}
bool bfs(){
memset(lev, 0, sizeof(lev));
lev[ss] = 1;
d.push(ss);
while(!d.empty()){
int x=d.front();
d.pop();
for(int i=hea[x]; i!=-1; i=edge[i].nxt){
int t=edge[i].too;
if(!lev[t] && edge[i].val>0){
lev[t] = lev[x] + 1;
d.push(t);
}
}
}
return lev[tt]!=0;
}
int dfs(int x, int lim){
if(x==tt) return lim;
int addFlow=0;
for(int &i=cur[x]; i!=-1; i=edge[i].nxt){
int t=edge[i].too;
if(lev[t]==lev[x]+1 && edge[i].val>0){
int tmp=dfs(t, min(lim-addFlow, edge[i].val));
edge[i].val -= tmp;
edge[i^1].val += tmp;
addFlow += tmp;
if(addFlow==lim) break;
}
}
return addFlow;
}
void dinic(){
while(bfs()){
for(int i=ss; i<=tt; i++) cur[i] = hea[i];
maxFlow += dfs(ss, oo);
}
}
int main(){
memset(hea, -1, sizeof(hea));
cin>>n;
ss = 0; tt = n + n * n + 1;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++){
scanf("%d", &uu);
ans += uu;
int p=(i-1)*n+j;
addEdge(ss, p, uu);
addEdge(p, n*n+i, oo);
addEdge(p, n*n+j, oo);
}
for(int i=1; i<=n; i++){
scanf("%d", &uu);
addEdge(n*n+i, tt, uu);
}
dinic();
cout<<ans-maxFlow<<endl;
return 0;
}