Description
You want to visit a strange country. There are n cities in the country. Cities are numbered from 1 to n. The unique way to travel in the country is taking planes. Strangely, in this strange country, for every two cities A and B, there is a flight from A to B or from B to A, but not both. You can start at any city and you can finish your visit in any city you want. You want to visit each city exactly once. Is it possible?
Input
There are multiple test cases. The first line of input is an integer T (0 < T <= 100) indicating the number of test cases. Then T test cases follow. Each test case starts with a line containing an integer n (0 < n <= 100), which is the number of cities. Each of the next n * (n - 1) / 2 lines contains 2 numbers A, B (0 < A, B <= n, A != B), meaning that there is a flight from city A to city B.
Output
For each test case:
- If you can visit each city exactly once, output the possible visiting order in a single line please. Separate the city numbers by spaces. If there are more than one orders, you can output any one.
- Otherwise, output "Impossible" (without quotes) in a single line.
Sample Input
3 1 2 1 2 3 1 2 1 3 2 3
Sample Output
1 1 2 1 2 3
很惭愧,我看到这个题就以为它是图论的某一个点,自己肯定不会,所有就没怎么想,其实
想想自己应该好好去试试的,其实这个题目并不难的,用DFS就可以过了,但是比赛的时候
真的是想不到啊,惭愧啊!!!,基本的DFS查找路径题目,也可以用哈密顿路来过,都行的
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int map[105][105];//那些路是可以走的 int vis[105];//这个数是不是已经走了 int rode[105];//把所有的路记下来 int n,count; //用count来计算到底走了多少个数了 int dfs(int x) { if(count==n) return 1; for(int i=1;i<=n;i++) { if(vis[i]==0&&map[x][i]) { vis[i]=1; count++; rode[count]=i; if(dfs(i)) return 1; vis[i]=0; count--; } } return 0; } int main() { int t; int i,j; scanf("%d",&t); while(t--) { memset(map,0,sizeof(map)); memset(vis,0,sizeof(vis)); memset(rode,0,sizeof(rode)); scanf("%d",&n); int a,b; int N=n*(n-1)/2; for(i=1;i<=N;i++) { scanf("%d%d",&a,&b); map[a][b]=1; } int flag=0; for(i=1;i<=n;i++) { count=1; vis[i]=1; rode[1]=i; if(dfs(i)) { flag=1; break; } vis[i]=0; } if(flag) { for(i=1;i<n;i++) printf("%d ",rode[i]); printf("%d\n",rode[n]); } else { printf("Impossible\n"); } } return 0; }