1137. Bus Routes

http://acm.timus.ru/problem.aspx?space=1&num=1137

任何一个线路都是一个环  任意两个环如果有至少一个共同的节点 则两个环可以扩展成一个大的环

只要用dfs搜一遍记录路径就可以了

代码:

#include<iostream>

#include<cstdio>

#include<cstring>

#include<algorithm>

#include<string>

#include<vector>

#include<map>

#include<queue>

#include<stack>

#include<cmath>

#define LL long long

//#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;



const int INF=0x3f3f3f3f;

//const int N=105;

const int M=1005;

const int L=10005;

vector<int>str[L];

vector<bool>visited[L];

vector<int>ans;

int a[M];

void dfs(int x,int k)

{

    for(unsigned int i=0;i<str[x].size();++i)

    {

        if(!visited[x][i])

        {

            visited[x][i]=true;

            ans.insert(ans.begin()+k,str[x][i]);

            dfs(str[x][i],k+1);

        }

    }

}

int main()

{

    //freopen("data.txt","r",stdin);



    int n;

    while(cin>>n)

    {

        int m;

        for(int i=1;i<L;++i)

        {str[i].clear();visited[i].clear();}

        int num=0;

        int st=-1;

        while(n--)

        {

            cin>>m;

            num+=m;

            for(int i=0;i<=m;++i)

            {

                cin>>a[i];

                if(st==-1)

                st=a[i];

                if(i)

                {

                    str[a[i-1]].push_back(a[i]);

                    visited[a[i-1]].push_back(false);

                }

            }

        }

        ans.clear();

        ans.push_back(st);

        dfs(st,1);

        if(num!=ans.size()-1)

        cout<<"0"<<endl;

        else

        {

            cout<<num;

            for(int i=0;i<ans.size();++i)

            cout<<" "<<ans[i];

            cout<<endl;

        }

    }

    return 0;

}

 

你可能感兴趣的:(Routes)