没想到codevs上的数据和我本地的数据是一样的……这下不用写多余的代码了
这道题和上一道题一样水,按照提议写成二分图就行。
1.源点向每个人连一条边,容量1,费用0,每个任务向汇点连一条边,容量1,费用0
2.每个人向每个任务连一条边,容量1,费用为cij
跑两次费用流就行
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
const int MAXN = 100000;
const int MAXM = 100000;
const int INF = 0x3f3f3f3f;
struct Edge
{
int from,to,next,cap,flow,cost;
} edge[MAXM];
int head[MAXN],tol;
int pre[MAXN],dis[MAXN];
bool vis[MAXN];
int N;//节点总个数,节点编号从0~N-1
void init(int n)
{
N = n;
tol = 0;
memset(head,-1,sizeof(head));
memset(edge,0,sizeof(edge));
}
void addedge(int u,int v,int cap,int cost)
{
edge[tol].from = u;
edge[tol].to = v;
edge[tol].cap = cap;
edge[tol].cost = cost;
edge[tol].flow = 0;
edge[tol].next = head[u];
head[u] = tol++;
edge[tol].to = u;
edge[tol].from = v;
edge[tol].cap = 0;
edge[tol].cost = -cost;
edge[tol].flow = 0;
edge[tol].next = head[v];
head[v] = tol++;
}
bool spfa(int s,int t)
{
queue<int>q;
for(int i = 0; i < N; i++)
{
dis[i] = INF;
vis[i] = false;
pre[i] = -1;
}
dis[s] = 0;
vis[s] = true;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].to;
if(edge[i].cap > edge[i].flow &&
dis[v] > dis[u] + edge[i].cost )
{
dis[v] = dis[u] + edge[i].cost;
pre[v] = i;
if(!vis[v])
{
vis[v] = true;
q.push(v);
}
}
}
}
if(pre[t] == -1)
return false;
else
return true;
}
//返回的是最大流,cost存的是最小费用
int minCostMaxflow(int s,int t,int &cost)
{
int flow = 0;
cost = 0;
while(spfa(s,t))
{
int Min = INF;
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to])
{
if(Min > edge[i].cap - edge[i].flow)
Min = edge[i].cap - edge[i].flow;
}
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to])
{
edge[i].flow += Min;
edge[i^1].flow -= Min;
cost += edge[i].cost * Min;
}
flow += Min;
}
return flow;
}
void print_all()
{
for(int i = 0; i<tol; i+=2)
{
printf("%d->%d cap = %d flow = %d cost = %d\n",edge[i].from,edge[i].to,edge[i].cap,edge[i].flow,edge[i].cost);
}
}
int c[1001][1001];
int main()
{
int n;
scanf("%d",&n);
for(int i = 1;i<=n;i++)
{
for(int j = 1;j<=n;j++)
{
scanf("%d",&c[i][j]);
}
}
init(2*n+2);
int st = 0,en = 2 *n + 1;
for(int i = 1;i<=n;i++)
{
addedge(0,i,1,0);
addedge(i + n, 2*n +1,1,0);
for(int j = 1;j<=n;j++)
{
addedge(i,j +n,1,c[i][j]);
}
}
int cost;
minCostMaxflow(0,2*n + 1,cost);
printf("%d\n",cost);
init(2*n+2);
st = 0,en = 2 *n + 1;
for(int i = 1;i<=n;i++)
{
addedge(0,i,1,0);
addedge(i + n, 2*n +1,1,0);
for(int j = 1;j<=n;j++)
{
addedge(i,j +n,1,-c[i][j]);
}
}
cost = 0;
minCostMaxflow(0,2*n + 1,cost);
printf("%d\n",-cost);
return 0;
}