把m个师傅拆成n个阶段,考虑每个人选上第某个阶段的某师傅对答案做出的贡献。
参见这里与那里。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int m, n, uu, cnt, hea[605], ss, tt, minCost, dis[605], pre[605];
bool vis[605];
queue<int> d;
struct Edge{
int too, nxt, val, cst;
}edge[100005];
void add_edge(int fro, int too, int val, int cst){
edge[cnt].nxt = hea[fro];
edge[cnt].too = too;
edge[cnt].val = val;
edge[cnt].cst = cst;
hea[fro] = cnt++;
}
void addEdge(int fro, int too, int val, int cst){
add_edge(fro, too, val, cst);
add_edge(too, fro, 0, -cst);
}
bool bfs(){
memset(pre, -1, sizeof(pre));
memset(dis, 0x3f, sizeof(dis));
dis[ss] = 0;
d.push(ss);
vis[ss] = true;
while(!d.empty()){
int x=d.front();
d.pop();
vis[x] = false;
for(int i=hea[x]; i!=-1; i=edge[i].nxt){
int t=edge[i].too;
if(dis[t]>dis[x]+edge[i].cst && edge[i].val>0){
dis[t] = dis[x] + edge[i].cst;
pre[t] = i;
if(!vis[t]){
vis[t] = true;
d.push(t);
}
}
}
}
return dis[tt]!=0x3f3f3f3f;
}
void dinic(){
while(bfs()){
int tmp=0x3f3f3f3f;
for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too])
tmp = min(tmp, edge[i].val);
for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too]){
edge[i].val -= tmp;
edge[i^1].val += tmp;
minCost += tmp * edge[i].cst;
}
}
}
int main(){
memset(hea, -1, sizeof(hea));
cin>>m>>n;
ss = 0; tt = m * n + n + 1;
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++){
scanf("%d", &uu);
for(int k=1; k<=n; k++)
addEdge(i, j*n+k, 1, uu*k);
}
for(int i=1; i<=n; i++)
addEdge(ss, i, 1, 0);
for(int i=1; i<=m; i++)
for(int j=1; j<=n; j++)
addEdge(i*n+j, tt, 1, 0);
dinic();
printf("%.2lf
", (double)minCost/n);
return 0;
}