POJ-1459 Power Network 网络流
题意:给定一些散列的源点会汇点,求解网络流。
代码如下:
#include <cstdlib> #include <cstring> #include <cstdio> #include <iostream> #include <algorithm> using namespace std; const int INF = 0x3fffffff; const int SS = 105, TT = 106; int n, np, nc, m; struct Edge { int v, c, next; }; Edge e[100000]; int idx, head[110]; int front, tail, que[110]; int lv[110]; void insert(int a, int b, int c) { e[idx].v = b, e[idx].c = c; e[idx].next = head[a]; head[a] = idx++; } void read_3(int &a, int &b, int &c) { char ch; while (ch = getchar(), ch != '(') ; scanf("%d,%d)%d", &a, &b, &c); // printf("%d %d %d\n", a, b, c); } void read_2(int &a, int &c) { char ch; while (ch = getchar(), ch != '(') ; scanf("%d)%d", &a, &c); // printf("%d %d\n", a, c); } bool bfs() { memset(lv, 0xff, sizeof (lv)); front = tail = 0; lv[SS] = 0; que[tail++] = SS; while (front < tail) { int u = que[front++]; for (int i = head[u]; i != -1; i = e[i].next) { if (!(~lv[e[i].v]) && e[i].c) { lv[e[i].v] = lv[u] + 1; if (e[i].v == TT) return true; que[tail++] = e[i].v; } } } return ~lv[TT]; } int dfs(int u, int sup) { if (u == TT) return sup; int tf = 0, f; for (int i = head[u]; i != -1; i = e[i].next) { if (lv[u]+1==lv[e[i].v] && e[i].c && (f=dfs(e[i].v, min(e[i].c, sup-tf)))) { tf += f; e[i].c -= f, e[i^1].c += f; if (tf == sup) return sup; } } if (!tf) lv[u] = -1; return tf; } int dinic() { int ret = 0; while (bfs()) { ret += dfs(SS, INF); // printf("ret = %d\n", ret); } return ret; } int main() { int a, b, c; while (scanf("%d %d %d %d", &n, &np, &nc, &m) != EOF) { idx = 0; memset(head, 0xff, sizeof (head)); for (int i = 0; i < m; ++i) { // m条边 read_3(a, b, c); insert(a, b, c); insert(b, a, 0); } for (int i = 0; i < np; ++i) { read_2(a, c); insert(SS, a, c); insert(a, SS, 0); } for (int i = 0; i < nc; ++i) { read_2(a, c); insert(a, TT, c); insert(TT, a, 0); } printf("%d\n", dinic()); } return 0; }