算法1
二分+最大流分层见图,好题
C++ 代码
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 60 * 110, M = (1 + 110 + N + 2450 * 110) * 2, INF = 0x3f3f3f3f;
int n, m, C, S, T;
int h[N], ne[M], e[M], f[M], idx;
int d[N], q[N], cur[N], hh, tt;
struct Edge{
int a, b, w;
}edges[2500];
void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], f[idx] = c, h[a] = idx ++;
e[idx] = a, ne[idx] = h[b], f[idx] = 0, h[b] = idx ++;
}
bool bfs()
{
memset(d, -1, sizeof d);
hh = 0, tt = 0;
q[0] = S, d[S] = 0, cur[S] = h[S];
while(hh <= tt)
{
int t = q[hh ++ ];
for(int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if(d[j] == -1 && f[i])
{
d[j] = d[t] + 1;
cur[j] = h[j];
if(j == T) return true;
q[ ++ tt ] = j;
}
}
}
return false;
}
int find(int u, int limit)
{
if(u == T) return limit;
int flow = 0;
for(int i = cur[u]; ~i && flow < limit; i = ne[i])
{
int v = e[i];
cur[u] = i;
if(f[i] && d[v] == d[u] + 1)
{
int r = find(v, min(f[i], limit - flow));
if(!r) d[v] = -1;
flow += r, f[i] -= r, f[i ^ 1] += r;
}
}
return flow;
}
int dinic()
{
int res = 0;
while(bfs()) res += find(S, INF);
return res;
}
bool check(int mid)
{
memset(h, -1, sizeof h);
idx = 0;
S = 0, T = (mid + 1) * n + 1;
add(S, 1, C);
for(int i = 0; i <= mid; ++ i)
add((i + 1) * n, T, INF);
for(int i = 0; i < mid; ++ i)
for(int j = 1; j <= n; ++ j)
add(i * n + j, (i + 1) * n + j, INF);
for(int i = 0; i < mid; ++ i)
for(int j = 0; j < m; ++ j)
{
int a = edges[j].a, b = edges[j].b, w = edges[j].w;
add(n * i + a, n * (i + 1) + b, w);
}
return dinic() >= C;
}
int main()
{
scanf("%d %d %d", &n, &m, &C);
int l = 1, r = n + C;
for(int i = 0; i < m; ++ i)
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
edges[i] = {a, b, c};
}
while(l < r)
{
int mid = (l + r) / 2;
if(check(mid)) r = mid;
else l = mid + 1;
}
printf("%d", r);
}