Cod sursa(job #2617314)

Utilizator betybety bety bety Data 21 mai 2020 14:05:55
Problema Taramul Nicaieri Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.72 kb

#include<fstream>

#include<vector>

#include<queue>



using namespace std;



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



typedef vector< int > graf;



const int nmax = 2 + 2 * 100;

int S, D;

int t[ nmax + 1 ];

int f[ nmax + 1 ][ nmax + 1 ], c[ nmax + 1 ][ nmax + 1 ];

graf g[ nmax + 1 ];



inline int min2( int a, int b ) {

    return ( a < b ? a : b );

}

bool bfs() {

    queue< int > q;

    for( int i = S; i <= D; ++ i ) {

        t[ i ] = -1;

    }



    q.push( S );

    t[ S ] = 0;

    while ( !q.empty() ) {

        int x = q.front();

        q.pop();



        for( graf::iterator it = g[ x ].begin(); it != g[ x ].end(); ++ it ) {

            if ( t[ *it ] == -1 && f[ x ][ *it ] < c[ x ][ *it ] ) {

                t[ *it ] = x;

                q.push( *it );

            }

        }

    }



    return ( t[ D ] != -1 );

}

int main() {

    int n, ans;

    fin >> n;



    S = 1; D = 2 * n + 2;

    ans = 0;

    for( int i = 1; i <= n; ++ i ) {

        int x, y;

        fin >> x >> y;

        c[ S ][ i + 1 ] = x;

        g[ S ].push_back( i + 1 );

        g[ i + 1 ].push_back( S );



        c[ i + n + 1 ][ D ] = y;

        g[ i + n + 1 ].push_back( D );

        g[ D ].push_back( i + n + 1 );

        ans += x;

    }

    for( int i = 1; i <= n; ++ i ) {

        for( int j = n + 1; j <= n + n; ++ j ) {

            if ( i != j - n ) {

                g[ i + 1 ].push_back( j + 1 );

                g[ j + 1 ].push_back( i + 1 );

                c[ i + 1 ][ j + 1 ] = 1;

            }

        }

    }



    while ( bfs() ) {

        for( graf::iterator it = g[ D ].begin(); it != g[ D ].end(); ++ it ) {

            if ( f[ *it ][ D ] < c[ *it ][ D ] && t[ *it ] != -1 ) {

                int val = c[ *it ][ D ] - f[ *it ][ D ];

                for( int nod = *it; nod != S; nod = t[ nod ] ) {

                    val = min2( val, c[ t[ nod ] ][ nod ] - f[ t[ nod ] ][ nod ] );

                }



                f[ *it ][ D ] += val;

                f[ D ][ *it ] -= val;

                for( int nod = *it; nod != S; nod = t[ nod ] ) {

                    f[ t[ nod ] ][ nod ] += val;

                    f[ nod ][ t[ nod ] ] -= val;

                }

            }

        }

    }



    fout << ans << "\n";

    for( int i = 1; i <= n; ++ i ) {

        for( int j = 1; j <= n; ++ j ) {

            if ( f[ i + 1 ][ j + n + 1 ] == 1 ) {

                fout << i << " " << j << "\n";

            }

        }

    }

    fin.close();

    fout.close();

    return 0;

}