Problem Description
Input
首行一個數T(T <= 40),代表數據總數,接下來有T組數據。
每組數據:
第一行兩個數N,M(1 <= N,M <= 50)
接下來N行,每行M個數(範圍是0-10000的整數)
接下來一行有N個數Ki,表示第i行至少選Ki個元素(0 <= Ki <= M)
最後一行有M個數Kj,表示第j列至少選Kj個元素(0 <= Kj <= N)
Output
Sample Input
1 4 4 1 1 1 1 1 10 10 10 1 10 10 10 1 10 10 10 1 1 1 1 1 1 1 1
Sample Output
6
思路:超源向行連邊,容量爲m-Ki,費用爲0.列向超匯連邊,容量爲n-Kj,費用爲0.行列連容量爲1,費用爲-key的邊。當spfa找到的路徑cost>=0就可停止。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define maxn 3800
#define maxm 48000
#define inf 0x3f3f3f3f
int first[maxn];
int key[108][108];
int vv[maxm],ww[maxm],nxt[maxm],cst[maxm];
int e;
int pre[maxn],pos[maxn];
int dis[maxn],que[maxn*10];
bool vis[maxn];
inline int min(int a,int b)
{
return a > b?b:a;
}
void addEdge(int u,int v,int w,int cost)
{
vv[e] = v;
ww[e] = w;
cst[e] = cost;
nxt[e] = first[u];
first[u] = e++;
vv[e] = u;
ww[e] = 0;
cst[e] = -cost;
nxt[e] = first[v];
first[v] = e++;
}
int spfa(int s,int t)
{
memset(pre,-1,sizeof(pre));
memset(vis,0,sizeof(vis));
int head,tail;
head = tail = 0;
for(int i = 0;i < maxn;i++)
dis[i] = inf;
que[tail++] = s;
pre[s] = s;
dis[s] = 0;
vis[s] = 1;
while(head < tail)
{
int u = que[head++];
vis[u] = 0;
for(int i = first[u];i != -1;i = nxt[i])
{
int v = vv[i];
if(ww[i] > 0 && dis[u] + cst[i] < dis[v])
{
dis[v] = dis[u] + cst[i];
pre[v] = u;
pos[v] = i;
if(!vis[v])
{
vis[v] = 1;
que[tail++] = v;
}
}
}
}
return pre[t] != -1;
}
int MinCostFlow(int s,int t,int flow)
{
int cost = 0;
int nowflow = 0;
while(spfa(s,t))
{
int f = inf;
for(int i = t;i != s;i = pre[i])
if(ww[pos[i]] < f) f = ww[pos[i]];
if(dis[t] >= 0) break;
f = min(flow - nowflow,f);
nowflow += f; cost += dis[t]*f;
for(int i = t;i != s;i = pre[i])
{
ww[pos[i]] -= f;
ww[pos[i]^1] += f;
}
if(nowflow == flow) break;
}
return cost;
}
int main()
{
//freopen("in.txt","r",stdin);
int t;
scanf("%d",&t);
while(t--)
{
int n,m;
scanf("%d%d",&n,&m);
e = 0;
memset(first,-1,sizeof(first));
int sum = 0;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= m;j++)
{
int a; scanf("%d",&a);
sum += a;
addEdge(i,n+j,1,-a);
}
}
for(int i = 1;i <= n;i++)
{
int a; scanf("%d",&a);
addEdge(0,i,m-a,0);
}
for(int i = 1;i <= m;i++)
{
int a; scanf("%d",&a);
addEdge(n+i,n+m+1,n-a,0);
}
int fuck = MinCostFlow(0,n+m+1,inf);
printf("%d\n",sum+fuck);
}
}