UVa 10596 - Morning Walk 有向图的欧拉回路

Problem H

Morning Walk

Time Limit

3 Seconds

 

Kamal is a Motashota guy. He has got a new job in Chittagong. So, he has moved to Chittagong from Dinajpur. He was getting fatter in Dinajpur as he had no work in his hand there. So, moving to Chittagong has turned to be a blessing for him. Every morning he takes a walk through the hilly roads of charming city Chittagong. He is enjoying this city very much. There are so many roads in Chittagong and every morning he takes different paths for his walking. But while choosing a path he makes sure he does not visit a road twice not even in his way back home. An intersection point of a road is not considered as the part of the road. In a sunny morning, he was thinking about how it would be if he could visit all the roads of the city in a single walk. Your task is to help Kamal in determining whether it is possible for him or not.

 

Input

Input will consist of several test cases. Each test case will start with a line containing two numbers. The first number indicates the number of road intersections and is denoted by N (2 ≤ N ≤ 200). The road intersections are assumed to be numbered from 0 to N-1. The second number R denotes the number of roads (0 ≤ R ≤ 10000). Then there will be R lines each containing two numbers c1 and c2 indicating the intersections connecting a road.

 

Output

Print a single line containing the text “Possible” without quotes if it is possible for Kamal to visit all the roads exactly once in a single walk otherwise print “Not Possible”.

 

Sample Input

Output for Sample Input

2 2

0 1

1 0

2 1

0 1

Possible

Not Possible

 

Problemsetter: Muhammad Abul Hasan

International Islamic University Chittagong


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

const int N=201, R=10000+5;

int n,r;
int g[N][N], d[N], vis[N];

bool isEuler()
{
	for(int i=1; i <= n; i++)
		if(d[i]%2)
			return false;
	return true;
}

void dfs(int u)
{
	vis[u]=1;
	for(int v=0; v < n; v++)
	{
		if(g[u][v] && !vis[v])
		{
			dfs(v);
		}
	}
}
// 判断是否存在回路 
bool isCycle()
{
	int count=0;
	for(int i=0; i < n; i++)
	{
		if(!vis[i])
		{
			count++;
			dfs(i);
		}
		
	}
	if(count>1)	return false;
	return true;
}

void init()
{
	memset(g, 0, sizeof(g));
	memset(d, 0, sizeof(d));
	memset(vis, 0, sizeof(vis));
}

int main()
{
//	freopen("in.txt","r",stdin);
	while(cin>>n>>r)
	{
		init();	
		int u,v;		
		for(int i=1; i <= r; i++)
		{
			cin>>u>>v;
			d[u]++;
			d[v]++;
			g[u][v]=g[v][u]=1;	
		}
		if(r==1){
			cout << "Not Possible" << endl;
			continue;
		}
		if(isCycle())
		
			if(isEuler())
				cout << "Possible" << endl;
			else 
				cout << "Not Possible" << endl;
		else 
			cout << "Not Possible" << endl;
			
	}
	return 0;
} 



你可能感兴趣的:(C++,算法,图,uva)