[TJOI2015]线性代数
第一次觉得我这么菜啊...菜是原罪
考虑把题目要求的式子拆开:
\[\begin{align}
(A*B-C)A^T&=A*B*A^T-C*A^T\\
&=\sum_{i=1}^n\sum_{j=1}^nb_{i,j}*a_j*a_i-\sum_{i=1}^nc_i*a_i
\end{align}
\]
我们不妨思考一下这个式子的现实意义,相当于是说如果你选一个点,会产生\(c_i\)的代价,如果选两个点,会产生\(b_{i,j}\)的收益,最大化收益与价值的差.
然后直接网络流建边就行了.
/*
mail: mleautomaton@foxmail.com
author: MLEAutoMaton
This Code is made by MLEAutoMaton
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define ll long long
#define re register
#define int ll
#define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
inline int gi(){
int f=1,sum=0;char ch=getchar();
while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
return f*sum;
}
const int N=1010,Inf=1e9+10;
int id[N][N],b[N][N],c[N],n,s,t,front[N*N],cnt,cur[N*N],dep[N*N];
queue<int>Q;
struct node{int to,nxt,w;}e[N*N<<1];
void Add(int u,int v,int w){
e[cnt]=(node){v,front[u],w};front[u]=cnt++;
e[cnt]=(node){u,front[v],0};front[v]=cnt++;
}
bool bfs(){
Q.push(s);memset(dep,0,sizeof(dep));dep[s]=1;
while(!Q.empty()){
int u=Q.front();Q.pop();
for(int i=front[u];~i;i=e[i].nxt){
int v=e[i].to;
if(!dep[v] && e[i].w){
dep[v]=dep[u]+1;Q.push(v);
}
}
}
return dep[t];
}
int dfs(int u,int flow){
if(u==t || !flow)return flow;
for(int &i=cur[u];~i;i=e[i].nxt){
int v=e[i].to;
if(dep[v]==dep[u]+1 && e[i].w){
int di=dfs(v,min(flow,e[i].w));
if(di){
e[i].w-=di;e[i^1].w+=di;
return di;
}
else dep[v]=0;
}
}
return 0;
}
int Dinic(){
int flow=0;
while(bfs()){
for(int i=s;i<=t;i++)cur[i]=front[i];
while(int d=dfs(s,Inf))flow+=d;
}
return flow;
}
signed main(){
#ifndef ONLINE_JUDGE
freopen("in.in","r",stdin);
#endif
n=gi();int tot=0,ans=0;memset(front,-1,sizeof(front));
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
b[i][j]=gi(),id[i][j]=++tot;
ans+=b[i][j];
}
for(int i=1;i<=n;i++)c[i]=gi();
s=0;t=n+tot+1;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
Add(s,id[i][j],b[i][j]);
Add(id[i][j],i+tot,Inf);
if(j!=i)Add(id[i][j],j+tot,Inf);
}
for(int i=1;i<=n;i++)Add(tot+i,t,c[i]);
printf("%lld\n",ans-Dinic());
return 0;
}