URAL 1137Bus Routes (dfs)

Z - Bus Routes
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

Description

Several bus routes were in the city of Fishburg. None of the routes shared the same section of road, though common stops and intersections were possible. Fishburg old residents stated that it was possible to move from any stop to any other stop (probably making several transfers). The new mayor of the city decided to reform the city transportation system. He offered that there would be only one route going through all the sections where buses moved in the past. The direction of movement along the sections must be the same and no additional sections should be used.
Write a program, which creates one of the possible new routes or finds out that it is impossible.

Input

The first line of the input contains the number of old routes n. Each of the following n lines contains the description of one route: the number of stops m and the list of that stops. Bus stops are identified by positive integers not exceeding 10000. A route is represented as a sequence of m + 1 bus stop identifiers: l1, l2, …, lm, lm+1 =  l1 that are sequentially visited by a bus moving along this route. A route may be self-intersected. A route always ends at the same stop where it starts (all the routes are circular).
The number of old routes: 1 ≤ n ≤ 100.
The number of stops: 1 ≤ m ≤ 1000.
The number-identifier of the stop: 1 ≤ l ≤ 10000.

Output

The output contains the number of stops in the new route k and the new route itself in the same format as in the input. The last ( k+1)-th stop must be the same as the first. If it is impossible to make a new route according to the problem statement then write 0 (zero) to the output.

Sample Input

inputoutput
3
6 1 2 5 7 5 2 1
4 1 4 7 4 1
5 2 3 6 5 4 2
15 2 5 4 2 3 6 5 7 4 1 2 1 4 7 5 2

Notes

Here is a picture for the example:
Problem illustration
题意就是给你几条旧的路线,让你求能否设计一条新的路线,可以包含这里面的所有路线,dfs变换一下就可以了,但是注意一点就是再回塑的时候不要把标记vis即系清空
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
#define N 10010
int n,m;
vector<int>ed[N];
bool vis[N][N];
int pa[100010],t;
void dfs(int u){   
     int i;
    for(i = 0 ;i < (int)ed[u].size() ; i++){
        int v = ed[u][i];
        if(!vis[u][v]){
            vis[u][v] = 1;
            dfs(v);
        }
    }
    t++;
    pa[t] = u;    
    return ;
}
int main(){
    int i,j,u,v;
    scanf("%d",&n);
    int sum=0;
    for(i = 1; i <= n ; i++){
        scanf("%d",&m);
        sum+=m;
        scanf("%d",&u);
        for(j = 1 ; j <= m ; j++)
        {
            scanf("%d",&v);
            ed[u].push_back(v);
            u = v;
        }
    }
    dfs(1);
    if(sum!=t-1)
        printf("0
");
    else{
    printf("%d
",t-1);
    for(i = t; i > 1 ; i--)
    printf("%d ",pa[i]);
    printf("%d
",pa[1]);
    }
    return 0;
}

            
原文地址:https://www.cnblogs.com/13224ACMer/p/4847255.html