”赛码杯“ Exploration
Miceren likes exploration and he found a huge labyrinth underground!
This labyrinth has N caves and some tunnels connecting some pairs of caves.
There are two types of tunnel, one type of them can be passed in only one direction and the other can be passed in two directions. Tunnels will collapse immediately after Miceren passing them.
Now, Miceren wants to choose a cave as his start point and visit at least one other cave, finally get back to start point.
As his friend, you must help him to determine whether a start point satisfing his request exists.
The first line contains a single integer T, indicating the number of test cases.
Each test case begins with three integers N, M1, M2, indicating the number of caves, the number of undirectional tunnels, the number of directional tunnels.
The next M1 lines contain the details of the undirectional tunnels. Each line contains two integers u, v meaning that there is a undirectional tunnel between u, v. (u ≠ v)
The next M2 lines contain the details of the directional tunnels. Each line contains integers u, v meaning that there is a directional tunnel from u to v. (u ≠ v)
T is about 100.
1 ≤ N,M1,M2 ≤ 1000000.
There may be some tunnels connect the same pair of caves.
The ratio of test cases with N > 1000 is less than 5%.
For each test queries, print the answer. If Miceren can do that, output "YES", otherwise "NO".
2 5 2 1 1 2 1 2 4 5 4 2 2 1 2 2 3 4 3 4 1
YES NO
#include <iostream> #include <stdio.h> #include <vector> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; bool visit[1000010],flag[1000010],USE[2000010]; int x[2000010],y[2000010],NEXT[3000010],value[3000010],h[1000010]; int n,m1,m2,top; bool success; void addedge(int u, int v) { ++top; NEXT[top]=h[u]; value[top]=v; h[u]=top; } void DFS(int k) { if (success) return; visit[k]=true; int q=h[k]; while(q!=-1) { int u=value[q],to; if (USE[u]) { q=NEXT[q]; continue; } if (x[u]==k) to=y[u]; else to=x[u]; if (flag[to]) { success=true; return; } if (visit[to]) { q=NEXT[q]; continue; } flag[to]=true; USE[u]=true; DFS(to); flag[to]=false; USE[u]=false; q=NEXT[q]; } } int main() { int T; scanf("%d",&T); while(T--) { scanf("%d%d%d",&n,&m1,&m2); top=0; for (int i=1;i<=n;i++) { visit[i]=false; h[i]=-1; } for (int i=1;i<=m1;i++) { scanf("%d%d",&x[i],&y[i]); addedge(x[i],i); addedge(y[i],i); } for (int i=m1+1;i<=m1+m2;i++) { scanf("%d%d",&x[i],&y[i]); addedge(x[i],i); } success=false; for (int i=1;i<=n;i++) { flag[i]=true; if (!visit[i]) DFS(i); flag[i]=false; if (success) { printf("YES\n"); break; } } if (!success) { printf("NO\n"); } } return 0; }
浙公网安备 33010602011771号