POJ 1637 Sightseeing tour(最大流)
生活随笔
收集整理的這篇文章主要介紹了
POJ 1637 Sightseeing tour(最大流)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
POJ 1637 Sightseeing tour
題目鏈接
題意:給一些有向邊一些無向邊,問能否把無向邊定向之后確定一個歐拉回路
思路:這題的模型很的巧妙,轉一個http://blog.csdn.net/pi9nc/article/details/12223693
先把有向邊隨意定向了,然后依據每一個點的入度出度之差,能夠確定每一個點須要調整的次數,然后中間就是須要調整的邊,容量為1,這樣去建圖最后推斷從源點出發的邊是否都滿流就可以
代碼:
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std;const int MAXNODE = 205; 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];int cur[MAXNODE];vector<int> cut;void init(int n) {this->n = n;memset(first, -1, sizeof(first));m = 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;}bool Maxflow(int s, int t) {this->s = s; this->t = t;Type flow = 0;while (bfs()) {for (int i = 0; i < n; i++)cur[i] = first[i];flow += dfs(s, INF);}for (int i = first[0]; i + 1; i = next[i])if (edges[i].flow != edges[i].cap) return false;return true;}void MinCut() {cut.clear();for (int i = 0; i < m; i += 2) {if (vis[edges[i].u] && !vis[edges[i].v])cut.push_back(i);}} } gao;const int N = 205; const int M = 1005;int t, n, m, in[N], out[N]; int u[M], v[M], w[M];bool solve() {gao.init(n + 2);for (int i = 1; i <= n; i++) {if ((in[i] + out[i]) % 2) return false;if (in[i] > out[i]) gao.add_Edge(i, n + 1, (in[i] - out[i]) / 2);if (out[i] > in[i]) gao.add_Edge(0, i, (out[i] - in[i]) / 2);}for (int i = 0; i < m; i++) {if (w[i]) continue;gao.add_Edge(u[i], v[i], 1);}return gao.Maxflow(0, n + 1); }int main() {scanf("%d", &t);while (t--) {scanf("%d%d", &n, &m);memset(in, 0, sizeof(in));memset(out, 0, sizeof(out));for (int i = 0; i < m; i++) {scanf("%d%d%d", &u[i], &v[i], &w[i]);in[v[i]]++;out[u[i]]++;}printf("%s\n", solve() ? "possible" : "impossible");}return 0; }
轉載于:https://www.cnblogs.com/mengfanrong/p/4298671.html
總結
以上是生活随笔為你收集整理的POJ 1637 Sightseeing tour(最大流)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring+Hibernate的典型配
- 下一篇: 数据库系列之T-SQL(存储过程)