Cod sursa(job #1788266)

Utilizator StarGold2Emanuel Nrx StarGold2 Data 25 octombrie 2016 20:57:36
Problema Santa Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.31 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <bitset>
using namespace std;

ifstream in ( "santa.in"  );
ofstream out( "santa.out" );

const int DIM = 5e4 + 5;

int low[DIM], lev[DIM];

vector<int> g[DIM], pa, ap, st, bc, aux;
bitset<DIM> ma, op; vector< vector<int> > bcc;

void dfs( int x, int f ) {
    ma[x] = 1; st.push_back( x );
    low[x] = lev[x] = lev[f] + 1;
    for( auto y : g[x] ) {
        if( y == f ) {
            continue; }
        if( ma[y] == 1 ) {
            low[x] = min( low[x], lev[y] ); }
        else {
            dfs( y, x ); op[x] = op[x] | op[y];
            low[x] = min( low[x], low[y] );
            if( lev[x] <= low[y] ) {
                aux.clear(); int z;
                do {
                    z = st.back(); st.pop_back();
                    aux.push_back( z );
                } while( z != y );
                aux.push_back( x );
                if( op[y] == 1 ) {
                    ap.push_back( x );
                    bcc.push_back( aux ); } } } }
    return; }

bool backt( int x, int z, int cnt, int sz ) {
    ma[x] = 1; if( cnt > 1 ) pa.push_back( x );
    if( cnt == sz && (z == -1 || x == z) )
        return true;
    for( auto y : g[x] ) {
        if( ma[y] == 0 && (cnt == sz - 1 || y != z) && backt( y, z, cnt + 1, sz ) ) {
            return true; } }
    pa.pop_back(); return false; }

int main( int argc, const char *argv[] ) {

    int n, m; in >> n >> m;
    for( int i = 1; i <= m; i ++ ) {
        int x, y; in >> x >> y;
        g[x].push_back( y );
        g[y].push_back( x ); }
    int s, e, q, ok = 1; in >> s >> e >> q;

    op[s] = 1; ap.push_back( s ); dfs( e, 0 );
    if( op[e] == 0 ) {
        ok = 0; }
    if( find( bcc[0].begin(), bcc[0].end(), q ) == bcc[0].end() ) {
        reverse( bcc[0].begin(), bcc[0].end() );
        reverse( ap.begin(), ap.end() ); }
    if( find( bcc[0].begin(), bcc[0].end(), q ) == bcc[0].end() ) {
        ok = 0; }

    ap[0] = q; ap[ap.size() - 1] = -1; pa.push_back( q );
    for( int i = 0; i < bcc.size(); i ++ ) {
        for( auto x : bcc[i] )
            ma[x] = 0;
        ok &= backt( ap[i], ap[i + 1], 1, bcc[i].size() ); }

    if( ok == 0 ) {
        out << "No chance" << endl;
        return 0; }
    out << pa.size() << endl;
    for( auto x : pa ) {
        out << x << " "; }
    out << endl;

    return 0; }