Cod sursa(job #1500801)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 12 octombrie 2015 18:26:49
Problema Critice Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.68 kb
#include<fstream>
#include<algorithm>
#include<vector>
#include<cstring>

using namespace std;

ifstream fin( "critice.in" ); ofstream fout( "critice.out" );

const int nmax = 1000;
const int mmax = 10000;
int start, dest;
int c[ nmax + 1 ][ nmax + 1 ], ind[ nmax + 1 ][ nmax + 1 ];
bool f[ nmax + 1 ];
int ant[ nmax + 1 ], init[ nmax + 1 ], q[ nmax + 1 ];
vector< int > g[ nmax + 1 ];
vector< int > ans;

struct str{
    int x, y, z;
    inline bool operator < ( const str &a ) const {
        return ( z < a.z );
    }
} muchii[ mmax + 1 ];

bool bfs() {
    int first, last;
    memset( f, 0, sizeof( f ) );
    memset( ant, 0, sizeof( ant ) );
    first = last = 0;

    f[ start ] = 1;
    q[ 0 ] = start;
    while ( first <= last && f[ dest ] == 0 ) {
        int x = q[ first ++ ];
        for( vector< int >::iterator it = g[ x ].begin(); it != g[ x ].end(); ++ it ) {
            if ( f[ *it ] == 0 && c[ x ][ *it ] ) {
                q[ ++ last ] = *it;
                f[ *it ] = 1;
                ant[ *it ] = x;
            }
        }
    }
    return f[ dest ];
}
int main() {
    int n, m;
    fin >> n >> m;

    start = 1; dest = n;
    for( int i = 0; i < m; ++ i ) {
        fin >> muchii[ i ].x >> muchii[ i ].y >> muchii[ i ].z;
        ind[ muchii[ i ].x ][ muchii[ i ].y ] = ind[ muchii[ i ].y ][ muchii[ i ].x ] = i + 1;
    }
    sort( muchii, muchii + m );
    for( int i = 0; i < m; ++ i ) {
        int x = muchii[ i ].x, y = muchii[ i ].y, z = muchii[ i ].z;
        g[ x ].push_back( y ); c[ x ][ y ] += z;
        g[ y ].push_back( x ); c[ y ][ x ] += z;
    }

    while ( bfs() ) {
        for( vector< int >::iterator it = g[ dest ].begin(); it != g[ dest ].end(); ++ it ) {
            if ( f[ *it ] == 1 && c[ *it ][ n ] ) {
                int tata, k = *it;
                int sol = c[ *it ][ n ];

                while ( (tata = ant[ k ]) ) {
                    if ( c[ tata ][ k ] < sol ) {
                        sol = c[ tata ][ k ];
                    }
                    k = tata;
                }

                c[ *it ][ n ] -= sol;
                c[ n ][ *it ] += sol;
                k = *it;
                while ( (tata = ant[ k ]) ) {
                    if ( c[ tata ][ k ] == sol ) {
                        ans.push_back( ind[ tata ][ k ] );
                    }
                    c[ tata ][ k ] -= sol;
                    c[ k ][ tata ] += sol;
                    k = tata;
                }
            }
        }
    }
    sort( ans.begin(), ans.end() );
    unique( ans.begin(), ans.end() );
    fout << ans.size() << "\n";
    for( int i = 0; i < ( int )ans.size(); ++ i ) {
        fout << ans[ i ] << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}