UVA - 10596 - Morning Walk(并查集判断连通图)
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 byN (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 c 1 and c 2 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
2 2
0 1
1 0
2 1
0 1
Sample Output
Possible
Not Possible
题意,给你n个点,m条边,让你判断这个有向图是不是一个欧拉回路(0 1 和 1 0是两条不同的路)
用搜索和并查集都能做,这次用并查集,如果是连通的图,每个点的代表元素都相同,不相同的话就不是连通的,再判断一下点的读数是不是偶数就搞定了
WA了一下,不知道错哪了,最后发现,m=0的情况没有考虑,没有路的时候肯定是not possible
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int uset[210], du[210];
int find(int x){
if(x!=uset[x])
uset[x] = find(uset[x]);
return uset[x];
}
int main()
{
int n, m;
while(scanf("%d %d", &n, &m)!=EOF){
for(int i = 0; i < n; i++){
du[i] = 0;
uset[i] = i;
}
if(!m){
printf("Not Possible\n");
continue;
}
for(int i = 0; i < m; i++){ //读入
int a, b;
scanf("%d %d", &a, &b);
du[a]++;
du[b]++;
a = find(a);
b = find(b);
if(a!=b)
uset[a] = b; //这个并不是启发式合并,因为数据不大
}
//判断是否连通
int j, flag1 = 0, flag2= 0;
for(j = 0; !du[j]; j++);
for(int i = j+1; i < n; i++){
if(du[i] && find(j) != find(i)){
flag1 = 1; //若是连通图说明每个点的代表元素都相同,不同则不连通
break;
}
}
//判断度数是否为偶数
if(!flag1){
for(int i = 0; i < n; i++)
if(du[i]%2){
flag2 = 1;
break;
}
}
if(flag1 || flag2)
printf("Not Possible\n");
else
printf("Possible\n");
}
return 0;
}
本文介绍了一道名为UVA-10596-MorningWalk的问题,通过并查集算法判断给定的有向图是否能够形成欧拉回路,即能否从任意一点出发经过所有边恰好一次回到起点。文章提供了完整的C++代码实现,并详细解释了算法思路。
1396

被折叠的 条评论
为什么被折叠?



