poj2112
二分加网络流,开始虽然写了floyd,但是没有调用,导致错了许多次。
View Code
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define N 300
#define inf 10000000
struct Edge
{
int x, y, nxt;
int c;
} bf[N * N];
int k, c, m, n, s, t;
int map[N][N];
int ne, head[N], cur[N], ps[N * N], dep[N];
void floyed()
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
for (int k = 1; k <= n; k++)
if (map[j][i] != inf && map[i][k] != inf)
if (map[j][i] + map[i][k] < map[j][k])
map[j][k] = map[j][i] + map[i][k];
}
void addedge(int x, int y, int c)
{
bf[ne].x = x;
bf[ne].y = y;
bf[ne].c = c;
bf[ne].nxt = head[x];
head[x] = ne++;
bf[ne].x = y;
bf[ne].y = x;
bf[ne].c = 0;
bf[ne].nxt = head[y];
head[y] = ne++;
}
int flow(int n, int s, int t)
{
int tr, res = 0;
int i, j, k, f, r, top;
while (1)
{
memset(dep, -1, n * sizeof(int));
for (f = dep[ps[0] = s] = 0, r = 1; f != r;)
for (i = ps[f++], j = head[i]; j; j = bf[j].nxt)
{
if (bf[j].c && -1 == dep[k = bf[j].y])
{
dep[k] = dep[i] + 1;
ps[r++] = k;
if (k == t)
{
f = r;
break;
}
}
}
if (-1 == dep[t])
break;
memcpy(cur, head, n * sizeof(int));
for (i = s, top = 0;;)
{
if ((i == t))
{
for (k = 0, tr = inf; k < top; ++k)
if (bf[ps[k]].c < tr)
tr = bf[ps[f = k]].c;
for (k = 0; k < top; ++k)
bf[ps[k]].c -= tr, bf[ps[k] ^ 1].c += tr;
res += tr;
i = bf[ps[top = f]].x;
}
for (j = cur[i]; cur[i]; j = cur[i] = bf[cur[i]].nxt)
if (bf[j].c && dep[i] + 1 == dep[bf[j].y])
break;
if (cur[i])
{
ps[top++] = cur[i];
i = bf[cur[i]].y;
}
else
{
if (0 == top)
break;
dep[i] = -1;
i = bf[ps[--top]].x;
}
}
}
return res;
}
bool ok(int d)
{
ne = 2;
memset(head, 0, sizeof(head));
s = 0;
t = n + 1;
for (int i = 1; i <= k; i++)
addedge(i, t, m);
for (int i = k + 1; i <= n; i++)
addedge(s, i, 1);
for (int i = k + 1; i <= n; i++)
for (int j = 1; j <= k; j++)
if (map[i][j] <= d)
addedge(i, j, 1);
int ret = flow(n + 2, s, t);
return (ret == c);
}
int binarysearch()
{
int l = 0;
int r = 20000;
int mid;
while (l < r)
{
mid = (l + r) / 2;
if (ok(mid))
r = mid;
else
l = mid + 1;
}
return l;
}
int main()
{
//freopen("t.txt", "r", stdin);
scanf("%d%d%d", &k, &c, &m);
n = c + k;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
scanf("%d", &map[i][j]);
if (map[i][j] == 0 && (i != j))
map[i][j] = inf;
}
floyed();
int ans = binarysearch();
printf("%d\n", ans);
return 0;
}