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 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个节点和r条路,节点从0开始标记。现在问你如果这个人想不走重复的路走完全部的路径是是否能够实现。
注意,要先判断有路径的节点是否相互连通!
#include <bits/stdc++.h>
using namespace std;
int Rank[1001],father[1001];
bool vis[1001];
int vertex[1001];
int n,r;
void ini()
{
memset(vis,false,sizeof(vis));
for(int i=0;i<n;i++)
{
father[i]=i;
Rank[i]=0;
}
}
int Find(int x)
{
if(father[x]==x)
return x;
else
return father[x]=Find(father[x]);
}
void unite(int x,int y)
{
int xx=Find(x);
int yy=Find(y);
if(xx==yy)
return;
if(Rank[xx]<Rank[yy])
father[xx]=yy;
else
{
father[yy]=xx;
if(Rank[xx]==Rank[yy])
Rank[xx]++;
}
}
bool judge()
{
int tmp=-1;
for(int i=0;i<n;i++)
father[i]=Find(i);
for(int i=0;i<n;i++)
if(vis[i])
{
tmp=father[i];
break;
}
for(int i=0;i<n;i++)
{
if(vis[i]&&tmp!=father[i])
return false;
}
for(int i=0;i<n;i++)
if(vertex[i]%2)
return false;
return true;
}
int main()
{
ios::sync_with_stdio(false);
while(cin>>n>>r)
{
ini();
memset(vertex,0,sizeof(vertex));
if(r==0)
{
cout<<"Not Possible"<<endl;
continue;
}
for(int i=1;i<=r;i++)
{
int a,b;
cin>>a>>b;
vis[a]=vis[b]=1;
unite(a,b);
vertex[a]++;
vertex[b]++;
}
if(judge())
cout<<"Possible"<<endl;
else
cout<<"Not Possible"<<endl;
}
return 0;
}
解答:
发现一道水题,赶紧做掉。结果总是过不了,看了看别人的解答,原来这题有好几个坑。首先要拥有路径的那些节点是否全部连通,没有路径的节点不用管了,如果不连通要输出Not Possible。
如果连通,直接判断欧拉回路即可。