大意不再赘述。
思路:
混合图的欧拉回路求解,具体步骤见另一篇博客:http://blog.csdn.net/wall_f/article/details/8237520
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <string> using namespace std; const int MAXN = 1010; const int MAXM = 50010; const int INF = 0x3f3f3f3f; struct Edge { int v, f; int next; }edge[MAXM]; int n, m; int cnt; int s, t; int first[MAXN], level[MAXN]; int q[MAXN]; int ind[MAXN], outd[MAXN]; int totFlow; void init() { cnt = 0; totFlow = 0; memset(first, -1, sizeof(first)); memset(ind, 0, sizeof(ind)); memset(outd, 0, sizeof(outd)); } void read(int u, int v, int f) { edge[cnt].v = v, edge[cnt].f = f; edge[cnt].next = first[u], first[u] = cnt++; } void read_graph(int u, int v, int f) { read(u, v, f); read(v, u, 0); } int bfs(int s, int t) { memset(level, 0, sizeof(level)); level[s] = 1; int front = 0, rear = 1; q[front] = s; while(front < rear) { int x = q[front++]; if(x == t) return 1; for(int e = first[x]; e != -1; e = edge[e].next) { int v = edge[e].v, f = edge[e].f; if(!level[v] && f) { level[v] = level[x] + 1; q[rear++] = v; } } } return 0; } int dfs(int u, int maxf, int t) { if(u == t) return maxf; int ret = 0; for(int e = first[u]; e != -1; e = edge[e].next) { int v = edge[e].v, f = edge[e].f; if(level[v] == level[u] + 1 && f) { int Min = min(maxf-ret, f); f = dfs(v, Min, t); edge[e].f -= f; edge[e^1].f += f; ret += f; if(ret == maxf) return ret; } } return ret; } int Dinic(int s, int t) { int ans = 0; while(bfs(s, t)) ans += dfs(s, INF, t); return ans; } void read_case() { init(); scanf("%d%d", &n, &m); while(m--) { int u, v, flag; scanf("%d%d%d", &u, &v, &flag); outd[u]++, ind[v]++; if(u != v) { if(!flag) read_graph(u, v, 1); } } } int build() { int flag = 1; s = 0, t = n+1; for(int i = 1; i <= n; i++) { if((ind[i]+outd[i]) & 1) //出度加入度是奇数 { return 0; } else if(outd[i] > ind[i]) //出度大于入度 { int dif = outd[i]-ind[i]; read_graph(s, i, dif/2); totFlow += dif/2; } //可能有入度等于出度的情况,连不连无所谓 else { int dif = ind[i]-outd[i]; read_graph(i, t, dif/2); } } return 1; } void solve() { read_case(); int flag = build(); int ans = Dinic(s, t); if(!flag) printf("impossible\n"); else if(ans >= totFlow) printf("possible\n"); else printf("impossible\n"); } int main() { int T; scanf("%d", &T); while(T--) { solve(); } return 0; }