1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #include <queue> #define MAXM (100000) #define MAXN (10000) #define rev(i) ((((i) - 1) ^ 1) + 1) using namespace std; struct fedg { int x, y, d; } rb[MAXM + 5]; struct edg { int from, to, next, cap, flow, xd; } b[MAXM * 20]; int g[MAXN * 2 + 5], cntb, s = MAXN * 2 + 1, t = MAXN * 2 + 2, n, m, dis[MAXN * 2 + 5], nd; void ade(int fr, int t, int ca, int dd) { b[++cntb] = {fr, t, g[fr], ca, 0, dd}; g[fr] = cntb; } bool bfs() { memset(dis, 0, sizeof(dis)); queue<int> q; q.push(s); dis[s] = 1; while (!q.empty()) { int now = q.front(); q.pop(); for (int i = g[now]; i; i = b[i].next) if (b[i].cap > b[i].flow && b[i].xd <= nd && !dis[b[i].to]) dis[b[i].to] = dis[now] + 1, q.push(b[i].to); } return dis[t]; } int dinic(int now, int maxf) { int re = 0, ri; if (now == t || !maxf) return maxf; for (int i = g[now]; i; i = b[i].next) if (b[i].xd <= nd && b[i].cap > b[i].flow && dis[b[i].to] == dis[now] + 1) { ri = dinic(b[i].to, min(maxf, b[i].cap - b[i].flow)); maxf -= ri; b[i].flow += ri; b[rev(i)].flow -= ri; re += ri; } return re; } bool cmp(fedg& x, fedg& y) { return x.d < y.d; } bool pd() { for (int i = 1; i <= cntb; i++) b[i].flow = 0; int re = 0; while (bfs()) re += dinic(s, n); return (re == n); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) ade(s, i, 1, 0), ade(i, s, 0, 0), ade(i + MAXN, t, 1, 0), ade(t, i + MAXN, 0, 0); for (int i = 1; i <= m; i++) { scanf("%d%d%d", &rb[i].x, &rb[i].y, &rb[i].d); ade(rb[i].x, rb[i].y + MAXN, 1, rb[i].d); ade(rb[i].y + MAXN, rb[i].x, 0, rb[i].d); } sort(rb + 1, rb + m + 1, cmp); int le = n, ri = m + 1, ans = m + 1; while (le <= ri) { int mi = (le + ri) >> 1; nd = rb[mi].d; if (pd()) ri = mi - 1, ans = mi; else le = mi + 1; } if (ans > m) puts("-1"); else printf("%d", rb[ans].d); return 0; }
|