ZSTU 4213: One-Way Roads【图论】【欧拉回路】

4213: One-Way Roads

Time Limit: 1 Sec   Memory Limit: 128 MB   Special Judge
Submit: 162   Solved: 56

Description

In the ACM kingdom, there are N cities connected by M two-way roads. These cities are connected, i.e., one can reach from any city X to any other city Y by going through some of these roads. One day, the government wishes to assign for each road a direction, such that one can still reach from any city to any other. You are asked to determine whether this task is possible.

Input

The first line of input contains T(0 ≤ T ≤ 100), the number of test cases. The first line of each test case consists of two integers, N(1 ≤ N ≤ 50), and M(1 ≤ M ≤ N(N − 1)/2). Each of the next M lines describes a road, and consists of two integers, X and Y(1 ≤ X, Y ≤ N; X ≠ Y), indicating that there is a road between city X and Y. There is at most one road that directly connects each pair of cities.

Output

For each test case, if it is impossible, output a single line NO. Otherwise, output YES on the first line, followed by M lines describing one possible direction assignment to these M roads. Each of these M lines should consist of two integers, XY, indicating that there is a one-way road from city X to city Y. These Mlines can be output in any order.

Sample Input

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

Sample Output

YES
1 2
2 3
3 1
NO
YES
1 2
2 3
3 4
4 1
2 4

HINT

Source



这题网上搜了下题解好像是求是否存在极大的双连通分量的。
这里用了欧拉回路的思想,如果全图双连通,那么肯定有一条欧拉回路,这样就能用打印欧拉回路的方法把每条边都给一个方向。全部给完后判断下图的连通性即可。

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

int n,m;

bool G[100][100],vis[100][100];
vector<pair<int , int > >ans;
void dfs(int u)
{
	for(int v=1 ; v<=n ; ++v)
	{
		if(G[u][v])
		{
			if(vis[u][v])continue;
			vis[u][v]=vis[v][u]=1;
			G[v][u]=0;
			ans.push_back(make_pair(u,v));
			dfs(v);
		}
	}
}
bool work()
{
	dfs(1);
	for(int i=0 ; i<ans.size() ; ++i)
	{
		G[ans[i].first][ans[i].second]=1;
	}
	for(int k=1 ; k<=n ; ++k)
		for(int i=1 ; i<=n ; ++i)
			for(int j=1 ; j<=n ; ++j)
				G[i][j] |= G[i][k] & G[k][j];
	for(int i=1 ; i<=n ; ++i)
		for(int j=1 ; j<=n ; ++j)
		{
			if(i!=j && G[i][j]==0)return 0;
		}
	return 1;
}
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		memset(vis,0,sizeof vis);
		memset(G,0,sizeof G);
		ans.clear();
		cin>>n>>m;
		while(m--)
		{
			int a,b;
			cin>>a>>b;
			G[a][b]=G[b][a]=1;
		}
		if(work())
		{
			cout<<"YES\n";
			for(int i=0 ; i<ans.size() ; ++i)
			{
				cout<<ans[i].first<<" "<<ans[i].second<<"\n";
			}
		}
		else cout<<"NO\n";
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值