ZOJ-3332-Strange Country II【7th浙江省赛】【dfs】

ZOJ-3332-Strange Country II

            Time Limit: 1 Second      Memory Limit: 32768 KB      Special Judge

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

题目链接:ZOJ-3332

题目大意:有n个城市,给出n * (n - 1) / 2条 有向 道路(A->B),问是否存在一条路径,是的走遍每个城市且不重复。

题目思路:DFS,详见代码。(这道题超时了好几次,发现忘记return了。。。╥﹏╥)

以下是代码:

#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
int city[200][200],road[200],vis[200];
int n, ok = 0;
void dfs(int first,int num)  //起始城市为first,到达第num个城市
{
    if (num == n)  //找到答案
    {
        ok = 1;
        return;
    }
    for (int i = 1; i <= n; i++)
    {
        if (!vis[i] && city[first][i] == 1)
        {
            vis[i] = 1;
            road[num + 1] = i;   //记录路径
            dfs(i,num+1);
            if (ok) return;  //记得return
            vis[i] = 0;
        }
    }
}
int main(){
    int t;
    cin >> t;
    while(t--)
    {
        ok = 0;
        scanf("%d",&n);
        memset(city,0,sizeof(city));    
        for (int i = 0; i < n * (n - 1) / 2; i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            city[a][b] = 1;
        }
        for (int i = 1; i <= n; i++)  //遍历起点城市
        {
            memset(vis,0,sizeof(vis));
            memset(road,0,sizeof(road));
            vis[i] = 1;
            road[1] = i;
            dfs(i,1);
            if (ok) break;
        }
        if (ok)
        {
            printf("%d",road[1]);
            for (int i = 2; i <= n; i++) printf(" %d",road[i]);
            printf("\n");
        }
        else printf("Impossible\n");
    }
    return 0;
}

你可能感兴趣的:(ZOJ,DFS,3332)