uva 10746 Crime Wave - The Sequel
题目大意:还记得上次那些抢银行的强盗吗?这次为了银行的安全,要派一些警察去守护这些银行。现在有n个银行和m警察,给出每个警察到达各个银行的时间,问说怎么样安排人手,可以使的警察到达银行的平均时间最小。
解题思路:建图是关键。设置一个超级源点连向所有的警察,容量为1,费用为0;设置一个超级汇点,使所有的银行连向超级汇点,容量为1, 费用为零。然后,连接所有警察和银行,费用为题目给出时间,容量为1。然后就是求最小费给最大流。这题不难没但是我WA了22发,精度!要注意精度!时间用double类型来储存,比较大小,判断相等的时候要注意,而且最后答案要加上0.001,因为该题精度为0.01。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 305;
const int OF = 100;
const int INF = 0x3f3f3f3f;
const int FIN = 205;
int n, m, s, t;
double time[N][N];
int a[N], pre[N], inq[N];
double d[N];
struct Edge{
int from, to, cap, flow;
double cos;
};
vector<Edge> edges;
vector<int> G[FIN * 2];
void addEdge(int from, int to, int cap, int flow, double cos) {
edges.push_back((Edge){from, to, cap, 0, cos});
edges.push_back((Edge){to, from, 0, 0, -cos});
int m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
void init() {
memset(time, 0, sizeof(time));
for (int i = 0; i < FIN * 2; i++) G[i].clear();
edges.clear();
}
void input() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%lf", &time[i][j]);
}
}
for (int i = 1; i <= m; i++) {
addEdge(s, i, 1, 0, 0);
}
for (int i = 1; i <= n; i++) {
addEdge(i + OF, t, 1, 0, 0);
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
addEdge(i, j + OF, 1, 0, time[j][i]);
}
}
}
int BF(int s, int t, int& flow, double& cost) {
queue<int> Q;
memset(inq, 0, sizeof(inq));
memset(a, 0, sizeof(a));
memset(pre, 0, sizeof(pre));
for (int i = 0; i < N; i++) d[i] = INF;
d[s] = 0;
a[s] = INF;
inq[s] = 1;
int flag = 1;
pre[s] = 0;
Q.push(s);
while (!Q.empty()) {
int u = Q.front(); Q.pop();
inq[u] = 0;
for (int i = 0; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (e.cap > e.flow && d[e.to] - d[u] - e.cos > 1e-6) {
d[e.to] = d[u] + e.cos;
a[e.to] = min(a[u], e.cap - e.flow);
pre[e.to] = G[u][i];
if (!inq[e.to]) {
inq[e.to] = 1;
Q.push(e.to);
}
}
}
flag = 0;
}
if (INF - d[t] < 1e-6) return 0;
flow += a[t];
cost += (double)d[t] * (double)a[t];
for (int u = t; u != s; u = edges[pre[u]].from) {
edges[pre[u]].flow += a[t];
edges[pre[u]^1].flow -= a[t];
}
return 1;
}
int MCMF(int s, int t, double& cost) {
int flow = 0;
cost = 0;
while (BF(s, t, flow, cost));
return flow;
}
int main() {
while (scanf("%d %d", &n, &m) == 2) {
if (n == 0 && m == 0) break;
s = 0, t = FIN;
double cost;
init();
input();
MCMF(s, t, cost);
printf("%.2lf\n", cost / n + 0.001);
}
return 0;
}