Cod sursa(job #2899139)

Utilizator Tudor06MusatTudor Tudor06 Data 8 mai 2022 00:35:03
Problema Cc Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.75 kb
#include <bits/stdc++.h>

using namespace std;

const int VMAX = 201;
const int INF = 2e9;

vector <int> edges[VMAX + 1];

int cost[VMAX + 1][VMAX + 1];
int flux[VMAX + 1][VMAX + 1];

int dist[VMAX + 1];
int fakedist[VMAX + 1];
int realdist[VMAX + 1];
bool viz[VMAX + 1];
int p[VMAX + 1];

bool inq[VMAX + 1];

int s, d, n;

void bellman() {
    for ( int i = 0; i <= d; i ++ ) dist[i] = INF;
    queue <int> q;
    q.push( s );
    dist[s] = 0;
    while ( !q.empty() ) {
        int node = q.front();
        q.pop();
        inq[node] = 0;
        for ( auto it : edges[node] ) {
            if ( flux[node][it] > 0 && dist[node] + cost[node][it] < dist[it] ) {
                dist[it] = dist[node] + cost[node][it];
                if ( !inq[it] ) {
                    q.push( it );
                    inq[it] = 1;
                }
            }
        }
    }
}
bool dijkstra() {
    for ( int i = 0; i <= d; i ++ ) {
        fakedist[i] = INF;
        realdist[i] = dist[i];
        p[i] = -2;
        viz[i] = 0;
    }
    p[s] = -1;
    dist[s] = fakedist[s] = 0;
    priority_queue <pair<int, int>> pq;
    pq.push( { 0, s } );
    while ( !pq.empty() ) {
        int node = pq.top().second;
        pq.pop();
        if ( viz[node] ) continue;
        viz[node] = 1;
        for ( auto it : edges[node] ) {
            if ( flux[node][it] > 0 && ( p[it] == -2 || fakedist[it] > fakedist[node] + realdist[node] + cost[node][it] - realdist[it] ) ) {
                fakedist[it] = fakedist[node] + realdist[node] + cost[node][it] - realdist[it];
                dist[it] = dist[node] + cost[node][it];
                p[it] = node;
                pq.push( { -fakedist[it], it } );
            }
        }
    }
    return ( fakedist[d] != INF );
}
int pump() {
    int c = 0;
    for ( int i = d; i != s; i = p[i] ) {
        c += cost[p[i]][i];
        flux[p[i]][i] --;
        flux[i][p[i]] ++;
    }
    return c;
}
int main() {
    ifstream fin( "cc.in" );
    ofstream fout( "cc.out" );
    int n;
    fin >> n;
    s = 0;
    d = 2 * n + 1;
    for ( int i = 1; i <= n; i ++ ) {
        for ( int j = n + 1; j <= 2 * n; j ++ ) {
            edges[i].push_back( j );
            edges[j].push_back( i );
            flux[i][j] = 1;
            fin >> cost[i][j];
            cost[j][i] = -cost[i][j];
        }
    }
    for ( int i = 1; i <= n; i ++ ) {
        edges[s].push_back( i );
        edges[i].push_back( s );
        edges[i + n].push_back( d );
        edges[d].push_back( i + n );
        flux[s][i] = 1;
        flux[i + n][d] = 1;
    }
    bellman();
    int mincost = 0;
    while ( dijkstra() ) {
        mincost += pump();
    }
    fout << mincost;
    return 0;
}