SPOJ_962
为了保证每个点只经过一次可以将点i拆成i和i',同时连一条i->i'的容量为1的边。
在添加边x<->y的时候,连y'->x和x'->y,最后将S连2',1'和3'连T,看最大流是否为2即可。
#include<stdio.h> #include<string.h> #include<algorithm> #define MAXD 60222 #define MAXM 460222 #define INF 0x3f3f3f3f int N, M, first[MAXD], e, next[MAXM], v[MAXM], flow[MAXM]; int S, T, d[MAXD], q[MAXD], work[MAXD]; void add(int x, int y, int z) { v[e] = y, flow[e] = z; next[e] = first[x], first[x] = e ++; } void init() { int i, x, y; scanf("%d%d", &N, &M); S = 0, T = 2 * N + 1; memset(first, -1, sizeof(first[0]) * (T + 1)); e = 0; for(i = 0; i < M; i ++) { scanf("%d%d", &x, &y); if(x > N || y > N) continue; add(N + x, y, 1), add(y, N + x, 0); add(N + y, x, 1), add(x, N + y, 0); } for(i = 1; i <= N; i ++) add(i, N + i, 1), add(N + i, i, 0); add(S, N + 2, 2), add(N + 2, S, 0); add(N + 1, T, 1), add(T, N + 1, 0), add(N + 3, T, 1), add(T, N + 3, 0); } int bfs() { int i, j, rear = 0; memset(d, -1, sizeof(d[0]) * (T + 1)); d[S] = 0, q[rear ++] = S; for(i = 0; i < rear; i ++) { for(j = first[q[i]]; j != -1; j = next[j]) if(flow[j] && d[v[j]] == -1) { d[v[j]] = d[q[i]] + 1, q[rear ++] = v[j]; if(v[j] == T) return 1; } } return 0; } int dfs(int cur, int a) { if(cur == T) return a; int t; for(int &i = work[cur]; i != -1; i = next[i]) if(flow[i] && d[v[i]] == d[cur] + 1) if(t = dfs(v[i], std::min(a, flow[i]))) { flow[i] -= t, flow[i ^ 1] += t; return t; } return 0; } int dinic() { int ans = 0, t; while(bfs()) { memcpy(work, first, sizeof(first[0]) * (T + 1)); while(t = dfs(S, INF)) ans += t; } return ans; } void solve() { if(N < 3 || dinic() != 2) printf("NO\n"); else printf("YES\n"); } int main() { int t; scanf("%d", &t); while(t --) { init(); solve(); } return 0; }