http://acm.hdu.edu.cn/showproblem.php?pid=5222

Problem Description

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.

 

 

Input

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%.

 

 

Output

For each test queries, print the answer. If Miceren can do that, output "YES", otherwise "NO".

 

 

Sample Input


 

2 5 2 1 1 2 1 2 4 5 4 2 2 1 2 2 3 4 3 4 1

 

 

Sample Output


 

YES NO

 

既有有向边,又有无向边。每条边只能走一次。

想用dfs的话,首先不能把无向边拆成2个有向边,因为每条边只能走一次就塌了。无向边有向边都用一条边+标记区分表示也不行,因为无向边本来两个方向都能走,这次从u扩展到v,下次不能在此基础上继续了,应该重新来从一开始跑,这样子时间上不可行。

 

因此换方法。先对无向边集合,用并查集维护点的连通性,在同一集合中的点相互可达。最后把所有的连通分量“缩点”,然后图就变成了DAG,运行一遍拓扑排序考察图是否有环。

#include<bits/stdc++.h>
using namespace std;
#define maxn 1000000+100

int T,n,m1,m2;
int p[maxn];
vector<int> G[maxn];
int c[maxn],topo[maxn],t;

int findset(int x){return x==p[x]?x:p[x]=findset(p[x]);}

bool init()
{
	bool finish=0;
	int u,v;
	cin>>n>>m1>>m2;
	for(int i=1;i<=n;i++)p[i]=i,G[i].clear();
	for(int i=0;i<m1;i++)
	{
		scanf("%d%d",&u,&v);
		u=findset(u);
		v=findset(v);
		if(u==v)finish=1;
		else p[u]=v;
	}
	for(int i=0;i<m2;i++)
	{
		scanf("%d%d",&u,&v);
		u=findset(u);
		v=findset(v);
		if(u==v)finish=1;
		else G[u].push_back(v);
	}
	return finish;
}

bool dfs(int u)
{
	c[u]=-1;
	int d=G[u].size();
	for(int i=0;i<d;i++)
	{
		int v=G[u][i];
		if(c[v]<0)return false;
		else if(!c[v]&&!dfs(v))return false;
	}
	c[u]=1;
	topo[--t]=u;
	return true;
}

bool toposort()
{
	t=n;
	memset(c,0,sizeof(c));
	for(int u=1;u<=n;u++)if(!c[u])
	{
		if(!dfs(u))return false;
	}
	return true;
}

int main()
{
	//freopen("input.in","r",stdin);
	cin>>T;
	while(T--)
	{
		if(init())cout<<"YES\n";
		else if(!toposort())cout<<"YES\n";
		else cout<<"NO\n";
	}
	return 0;
}