UVALive_4271
这个题目一开始把这个项链描述地既详细又神奇,但是后来仔细想一下,实际上只要S和T之间能够存在一条回路,即从S出发走到T再走回来,中途不经过重复的边,那么这条回路就可以看成是满足题目描述的项链。
想到这就好办了,为了保证路不重复用网络流就可以了,接下来就虚拟出一个源点S',连一条S'到S的容量为2的边,其余原图上的边容量都看成1,然后看S'到T的最大流是不是2就可以了。
#include#include #include #define MAXD 10010#define MAXM 200010#define INF 0x3f3f3f3fint N, M, first[MAXD], e, next[MAXM], v[MAXM], flow[MAXM];int S, T, q[MAXD], d[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, j, x, y; S = 0; memset(first, -1, sizeof(first[0]) * (N + 1)), e = 0; for(i = 0; i < M; i ++) { scanf("%d%d", &x, &y); add(x, y, 1), add(y, x, 1); } scanf("%d%d", &x, &T); add(S, x, 2), add(x, S, 0);}int bfs(){ int i, j, rear = 0; memset(d, -1, sizeof(d[0]) * (N + 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; for(int &i = work[cur]; i != -1; i = next[i]) if(flow[i] && d[v[i]] == d[cur] + 1) if(int 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]) * (N + 1)); while(t = dfs(S, INF)) ans += t; } return ans;}void solve(){ printf("%s\n", dinic() == 2 ? "YES" : "NO");}int main(){ int t = 0; while(scanf("%d%d", &N, &M), N) { init(); printf("Case %d: ", ++ t); solve(); } return 0; }