Cod sursa(job #2531328)

Utilizator memecoinMeme Coin memecoin Data 26 ianuarie 2020 06:36:26
Problema Cc Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.6 kb
#include <fstream>
#include <string>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <math.h>
#include <set>
#include <map>
#include <string.h>
#include <queue>

#define INF 0x3f3f3f3f

using namespace std;

#ifdef DEBUG
string name = "data";
#else
string name = "cc";
#endif

ifstream fin(name + ".in");
ofstream fout(name + ".out");

#define MAXN 351

int n, m, s, t;

int c[MAXN][MAXN];
int f[MAXN][MAXN];
int d[MAXN][MAXN];

vector<int> g[MAXN];

int parent[MAXN];

bool inQueue[MAXN];
int dist[MAXN];

bool bellmanFord() {
    memset(inQueue, false, sizeof(inQueue));
    memset(dist, 0x3f, sizeof(dist));
    
    queue<int> q;
    
    q.push(s);
    inQueue[s] = true;
    dist[s] = 0;
    bool reachedSink = false;
    
    while (!q.empty()) {
        auto node = q.front();
        q.pop();
        inQueue[node] = false;
        
        for (auto x: g[node]) {
            bool allowsFlow = f[node][x] != c[node][x];
            
            if (allowsFlow && (dist[x] > dist[node] + d[node][x])) {
                dist[x] = dist[node] + d[node][x];
                parent[x] = node;
                
                if (!inQueue[node]) {
                    q.push(x);
                    inQueue[x] = true;
                }
                
                if (x == t) {
                    reachedSink = true;
                }
            }
        }
    }
    
    return reachedSink;
}

int main() {
    
    fin >> n;
    
    s = 0;
    t = 2 * n + 1;
    
    for (int i = 1; i <= n; ++i) {
        g[s].push_back(i);
        g[i].push_back(s);
        c[s][i] = 1;
        
        g[t].push_back(n + i);
        g[n + i].push_back(t);
        c[n + i][t] = 1;
    }
    
    int x;
    
    for (int i = 1; i <= n; ++i) {
        for (int j = n + 1; j <= 2 * n; ++j) {
            fin >> x;
            g[i].push_back(j);
            g[j].push_back(i);
            c[i][j] = 1;
            d[i][j] = x;
            d[j][i] = -x;
        }
    }
    
    int flow = 0;
    int cost = 0;
    
    while (bellmanFord()) {
        int minFlow = INF;
        
        int node = t;
        
        while (node != s) {
            int p = parent[node];
            
            minFlow = min(minFlow, c[p][node] - f[p][node]);
            
            node = p;
        }
        
        node = t;
        
        while (node != s) {
            int p = parent[node];
            cost += minFlow * d[p][node];
            
            f[p][node] += minFlow;
            f[node][p] -= minFlow;
            
            node = p;
        }
        
        flow += minFlow;
    }
    
    fout << cost;
    
    return 0;
}