费用流水题
把工人和车之间建边,费用设为时间,流量设为1,求出最小费用再除以 n 就好了,建边比较恶心,这里写了半天
以下为 A C 代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
const int INF = 0x3f3f3f3f;
int n,m,s,t;
int mincost;
struct Edge
{
int next,to,dis,flow;
}ed[maxn<<1];
int tot=-1,head[maxn];
int pre[maxn];
int dis[maxn];
int vis[maxn];
int flow[maxn];
int last[maxn];
int mp[101][101];
void addedge(int from,int to,int flow,int dis)
{
ed[++tot].next=head[from];
ed[tot].dis=dis;
ed[tot].flow=flow;
ed[tot].to=to;
head[from]=tot;
}
void add(int x,int y,int f,int d)
{
addedge(x,y,f,d); addedge(y,x,0,-d);
}
bool spfa(int s,int t)
{
queue<int> q;
memset(dis,INF,sizeof dis);
memset(flow,INF,sizeof flow);
memset(vis,0,sizeof vis);
q.push(s);
vis[s]=1;
pre[t]=-1;
dis[s]=0;
while(q.size())
{
int now=q.front(); q.pop();
vis[now]=0;
for (int i=head[now]; ~i; i=ed[i].next)
{
if (ed[i].flow>0 && dis[ed[i].to]>dis[now]+ed[i].dis)//正边
{
dis[ed[i].to]=dis[now]+ed[i].dis;
flow[ed[i].to]=min(flow[now],ed[i].flow);
pre[ed[i].to]=now;
last[ed[i].to]=i;
if (!vis[ed[i].to])
{
vis[ed[i].to]=1;
q.push(ed[i].to);
}
}
}
}
return pre[t]!=-1;
}
void MCMF(int s,int t)
{
while(spfa(s,t))
{
int now=t;
mincost+=flow[t]*dis[t];
while(now!=s)
{
ed[last[now]].flow-=flow[t];
ed[last[now]^1].flow+=flow[t];
now=pre[now];
}
}
}
int main()
{
memset(head,-1,sizeof(head));
scanf("%d%d",&m,&n);
int S=0,T=n*m+n+1;
for (int i=1; i<=n; i++)
add(S,i,1,0);
for (int i=n+1; i<=n+m*n; i++)
add(i,T,1,0);
for (int i=1; i<=n; i++)
for (int j=1; j<=m; j++)
scanf("%d",&mp[i][j]);
for(int car=1; car<=n; car++)
{
int peo=1,num=0;
for(int i=n+1; i<=n+n*m; i++)
{
num++;
if(num>n) {num=1; peo++;}
add(car,i,1,mp[car][peo]*num);
}
}
MCMF(S,T);
printf("%.2lf",mincost/(n*1.0));
return 0;
}