UVA - 10596 Morning Walk (欧拉回路+dfs)

 

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


题意:
给出N个点和R条边,问能不能走完所有的边且每条边只走一次,点可以不走完。
解析:
deg记录每个点的度,用dfs查找第一个有度数的欧拉回路边和总边数是否相等。这题和项链那道题目很像,如果不能理解请参考上题的代码。

注意:
visit all the roads of the city in a single walk.
走完所有的边且每条边只走一次,点可以不走完,一直WA在这里。


#include <stdio.h>
#include <string.h>

const int N = 210;

int n,r;
int deg[N];
int edge[N][N];
int cnt;

//判断是否全为偶数节点
bool judge() {
	for(int i = 0; i < n; i++) {
		if( deg[i]%2 ) {
			return false;
		}
	}
	return true;
}

//标记访问过的节点
void dfs(int u) {
	for(int v = 0; v < n; v++) {
		if(edge[u][v]) {
			edge[u][v]--;	
			edge[v][u]--;
			dfs(v);
			cnt++;
		}
	}
}

int main() {
	int u,v;
	while(scanf("%d%d",&n,&r) != EOF) {
		if(!r) {
			printf("Not Possible\n");
			continue;
		}
		memset(deg,0,sizeof(deg));
		memset(edge,0,sizeof(edge));
		for(int i = 0; i < r; i++) {
			scanf("%d%d",&u,&v);
			edge[u][v]++;
			edge[v][u]++;
			deg[u]++;
			deg[v]++;
		}
		if( judge() ) {	
			cnt = 0;
			for(int i = 0; i < n; i++) {
				if(deg[i]) {
					dfs(i);
					break;
				}
			}
			if(cnt == r) {
				printf("Possible\n");
			}
			else{
				printf("Not Possible\n");
			}
		}else {		
			printf("Not Possible\n");
		}
	}
	return 0;
}


你可能感兴趣的:(uva,walk,Morning)