zoukankan      html  css  js  c++  java
  • ural Bus Routes(dfs深搜)

    题意:一个城市有N条公交线路,每条线路都是一个环,现在想将这些公交线路合成一条,问能不能合成一个环。

    思路:因为现在的每条公交线路已经是一个环了,只要两个环之间有一个公共点,就能从这个环到另一个环,但是有图不连通的情况,这种情况下直接输出0。这个有点坑人,明明给出的数据范围很大,但其实后台数据应该没那么大,如果 用数组会超内存,但有vector就不会,应该是测试数据范围比给出的要小。

    代码:

    View Code
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <iostream>
    #include <algorithm>
    #include <queue>
    #include <math.h>
    #include <map>
    #include <stack>
    #include <vector>
    #define  N 10004
    #define  M 100005
    using namespace std ;
    
    vector<int>p[N] ;
    vector<int>q ;
    vector<bool>vist[N] ;
    int n , sum ;
    
    void init()
    {
        for( int i = 0 ; i < N ; i++ )
        {
            p[i].clear() ;
            vist[i].clear() ;
        }
        q.clear();
        sum = 0 ;
    }
    
    void dfs( int x , int id )
    {
        for ( int i = 0 ; i < p[x].size() ; i++ )
        {
            if ( !vist[x][i] )
            {
                vist[x][i] = true ;
                q.insert( q.begin() + id , p[x][i] ) ;
                dfs( p[x][i] , id + 1 ) ;
            }
        }
    }
    
    int main()
    {
        int m , i , j , x , y , s ;
    
        init() ;
        s = M ;
        cin>>n ;
        for ( i = 1 ; i <= n ; i++ )
        {
            cin>>m>>x ;
            sum += m ;
            if ( x < s )
            s = x ;
            for ( j = 1 ; j <= m ; j ++ )
            {
                cin>>y ;
                p[x].push_back( y ) ;
                vist[x].push_back( false ) ;
                if ( y < s )
                s = y ;
                x = y ;
            }
        }
        q.push_back( s ) ;
        dfs( s , 1 );
        if( sum != q.size() - 1)
        {
            printf ( "0\n" ) ;
        }
        else
        {
            cout<<sum ;
            for( i = 0 ; i < q.size() ; i++ )
            {
                cout<<" "<<q[i];
            }
            cout<<endl ;
        }
        return 0 ;
    }
  • 相关阅读:
    实验二 结对编程
    实验一 GIT代码版本管理
    实验五-单元测试
    代码审查
    结对编程(第二阶段)
    实验一GIT代码版本管理
    2020综合实践 第6次实践作业 08组
    第五次系统综合实践
    第四次系统综合实践
    第三次系统综合实践
  • 原文地址:https://www.cnblogs.com/misty1/p/2882440.html
Copyright © 2011-2022 走看看