ZOJ 1324 Reactor Cooling——无源汇有上下界的可行流

网友投稿 248 2022-11-01


ZOJ 1324 Reactor Cooling——无源汇有上下界的可行流

#include #include #include #include #include #include using namespace std;const int maxn = 410;const int INF = 0x3f3f3f3f;int a[maxn], down[maxn*maxn];struct Edge { int from, to, flow, cap; Edge(int a, int b, int c, int d) : from(a), to(b), flow(c), cap(d) {}};struct Dinic { bool vis[maxn]; int n, m, s, t, d[maxn], cur[maxn]; vector edges; vector G[maxn]; void init(int nn) { n = nn; edges.clear(); for (int i = 0; i <= n + 5; i++) G[i].clear(); } void addedge(int from, int to, int flow, int cap) { edges.push_back(Edge(from, to, flow, cap)); edges.push_back(Edge(to, from, -flow, 0)); m = edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool bfs() { memset(vis, 0, sizeof(vis)); queue Q; Q.push(s); d[s] = 0; vis[s] = 1; while (!Q.empty()) { int x = Q.front(); Q.pop(); for (int i = 0; i < G[x].size(); i++) { Edge &e = edges[G[x][i]]; if (!vis[e.to] && e.cap > e.flow) { vis[e.to] = 1; d[e.to] = d[x] + 1; Q.push(e.to); } } } return vis[t]; } int dfs(int x, int a) { if (x == t || a == 0) return a; int flow = 0, f; for (int &i = cur[x]; i < G[x].size(); i++) { Edge &e = edges[G[x][i]]; if (d[x] + 1 == d[e.to] && (f=dfs(e.to, min(a, e.cap - e.flow))) > 0) { e.flow += f; edges[G[x][i]^1].flow -= f; flow += f; a -= f; if (a == 0) break; } } return flow; } int maxflow(int ss, int tt) { s = ss, t = tt; int flow = 0; while (bfs()) { memset(cur, 0, sizeof(cur)); flow += dfs(s, INF); } return flow; } void output(int m) { for (int i = 1; i <= m; i++) { printf("%d\n", down[i] + edges[(i-1)*2].flow); } }}dinic;int main() { int T, n, m, from, to, up; scanf("%d", &T); for (int kase = 1; kase <= T; kase++) { scanf("%d %d", &n, &m); dinic.init(n); memset(a, 0, sizeof(a)); for (int i = 1; i <= m; i++) { scanf("%d %d %d %d", &from, &to, &down[i], &up); dinic.addedge(from, to, 0, up - down[i]); a[from] -= down[i]; a[to] += down[i]; } int ss = n + 1, tt = n + 2, sum = 0; for (int i = 1; i <= n; i++) { if (a[i] > 0) { dinic.addedge(ss, i, 0, a[i]); } else { sum -= a[i]; dinic.addedge(i, tt, 0, -a[i]); } } if (kase != 1) printf("\n"); int temp = dinic.maxflow(ss, tt); if (temp != sum) { printf("NO\n"); } else { printf("YES\n"); dinic.output(m); } } return 0;}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:多线程_解决Runnable接口无start()方法的情况
下一篇:POJ 3046 Ant Counting——多重集组合数
相关文章

 发表评论

暂时没有评论,来抢沙发吧~