Cod sursa(job #1516497)

Utilizator Athena99Anghel Anca Athena99 Data 3 noiembrie 2015 08:55:17
Problema Cc Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.85 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

const int inf= 1<<30;
const int nmax= 100;
const int nmax2= nmax*2+2;

bool u[nmax2];
int n, s, d;
int p[nmax2], dist[nmax2], c[nmax2][nmax2], cost[nmax2][nmax2], f[nmax2][nmax2];

queue <int> q;
vector <int> v[nmax2];

bool bellmanford(  ) {
    for ( int i= s; i<=d; ++i ) {
        dist[i]= inf;
        p[i]= u[i]= 0;
    }
    dist[s]= 0;
    u[s]= 1;

    for ( q.push(s); !q.empty(); q.pop() ) {
        int x= q.front();
        for ( vector <int>::iterator it= v[x].begin(); it!=v[x].end(); ++it ) {
            if ( f[x][*it]<c[x][*it] && dist[x]+cost[x][*it]<dist[*it] ) {
                dist[*it]= dist[x]+cost[x][*it];
                p[*it]= x;
                if ( u[*it]==0 ) {
                    u[*it]= 1;
                    q.push(*it);
                }
            }
        }

        u[x]= 0;
    }

    return dist[d]!=inf;
}

int fmcm(  ) {
    int ans= 0;
    while ( bellmanford() ) {
        int fmin= inf;
        for ( int i= d; i!=s; i= p[i] ) {
            fmin= min(fmin, c[p[i]][i]-f[p[i]][i]);
        }
        for ( int i= d; i!=s; i= p[i] ) {
            f[p[i]][i]+= fmin;
            f[i][p[i]]-= fmin;
        }

        ans= ans+fmin*dist[d];
    }

    return ans;
}

void addedge( int x, int y, int z, int t ) {
    v[x].push_back(y);
    v[y].push_back(x);
    cost[x][y]= z;
    cost[y][x]= -z;
    c[x][y]= t;
}

int main(  ) {
    fin>>n;
    s= 0, d= n*2+1;
    for ( int i= 1; i<=n; ++i ) {
        for ( int j= 1, x; j<=n; ++j ) {
            fin>>x;
            addedge(i, n+j, x, 1);
        }
        addedge(s, i, 0, 1);
        addedge(n+i, d, 0, 1);
    }

    int sol= fmcm();
    fout<<sol<<"\n";

    return 0;
}