HDU 3157 Crazy Circuits(有源汇上下界最小流)

来源:互联网 发布:12306数据库 百度网盘 编辑:程序博客网 时间:2024/05/16 06:40

HDU 3157 Crazy Circuits

题目链接

题意:一个电路板,上面有N个接线柱(标号1~N),还有两个电源接线柱 + -,给出一些线路,每个线路有一个下限值求一个可以让所有部件正常工作的总电流 没有则输出impossible

思路:
有源汇有上下界求最小流,建模方法为:
按无源汇先建图,跑超级源汇ss->tt一次,然后加入t->s,容量INF的边,在跑一次ss->tt,如果是满流,就有解,解为t->s边的当前流量

顺带写个最大流的,最大流就先把t->s加入直接跑一下,t->s的流量就是了

代码:

#include <cstdio>#include <cstring>#include <queue>#include <algorithm>using namespace std;const int MAXNODE = 65;const int MAXEDGE = 10005;typedef int Type;const Type INF = 0x3f3f3f3f;struct Edge {int u, v;Type cap, flow;Edge() {}Edge(int u, int v, Type cap, Type flow) {this->u = u;this->v = v;this->cap = cap;this->flow = flow;}};struct Dinic {int n, m, s, t;Edge edges[MAXEDGE];int first[MAXNODE];int next[MAXEDGE];bool vis[MAXNODE];Type d[MAXNODE];Type flow;int cur[MAXNODE];void init(int n) {this->n = n;memset(first, -1, sizeof(first));m = 0;flow = 0;}void add_Edge(int u, int v, Type cap) {edges[m] = Edge(u, v, cap, 0);next[m] = first[u];first[u] = m++;edges[m] = Edge(v, u, 0, 0);next[m] = first[v];first[v] = m++;}bool bfs() {memset(vis, false, sizeof(vis));queue<int> Q;Q.push(s);d[s] = 0;vis[s] = true;while (!Q.empty()) {int u = Q.front(); Q.pop();for (int i = first[u]; i != -1; i = next[i]) {Edge& e = edges[i];if (!vis[e.v] && e.cap > e.flow) {vis[e.v] = true;d[e.v] = d[u] + 1;Q.push(e.v);}}}return vis[t];}Type dfs(int u, Type a) {if (u == t || a == 0) return a;Type flow = 0, f;for (int &i = cur[u]; i != -1; i = next[i]) {Edge& e = edges[i];if (d[u] + 1 == d[e.v] && (f = dfs(e.v, min(a, e.cap - e.flow))) > 0) {e.flow += f;edges[i^1].flow -= f;flow += f;a -= f;if (a == 0) break;}}return flow;}Type Maxflow(int s, int t) {this->s = s; this->t = t;while (bfs()) {for (int i = 0; i < n; i++)cur[i] = first[i];flow += dfs(s, INF);}return flow;}bool judge(int s) {for (int i = first[s]; i + 1; i = next[i])if (edges[i].flow != edges[i].cap) return false;return true;}} gao;const int N = 65;int n, m, s, t, ss, tt, du[N];char c[15];int main() {while (~scanf("%d%d", &n, &m) && n || m) {gao.init(n + 4);s = 0; t = n + 1; ss = n + 2; tt = n + 3;int u, v, w;memset(du, 0, sizeof(du));while (m--) {scanf("%s", c);if (c[0] == '+') u = s;else sscanf(c, "%d", &u);scanf("%s", c);if (c[0] == '-') v = t;else sscanf(c, "%d", &v);scanf("%d", &w);gao.add_Edge(u, v, INF);du[u] -= w;du[v] += w;}for (int i = s; i <= t; i++) {if (du[i] > 0) gao.add_Edge(ss, i, du[i]);if (du[i] < 0) gao.add_Edge(i, tt, -du[i]);}gao.Maxflow(ss, tt);gao.add_Edge(t, s, INF);gao.Maxflow(ss, tt);if (!gao.judge(ss)) printf("impossible\n");else printf("%d\n", gao.edges[gao.m - 2].flow);}return 0;}


1 0
原创粉丝点击