Cod sursa(job #3304783)

Utilizator Mihai_OctMihai Octavian Mihai_Oct Data 27 iulie 2025 11:45:23
Problema Cc Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.17 kb
#include <bits/stdc++.h>

using namespace std;

#define ST_DIO 0
#if ST_DIO
    #define fin cin
    #define fout cout
#else
    ifstream fin("cc.in");
    ofstream fout("cc.out");
#endif  // ST_DIO

const int INF = 1e9 + 7;
int n, m, i, j, st, sf, flux[202][202], rasp;
int taxa[202], tata[202], cost[202][202];
vector<int> gr[202];
bool fr[102];

static inline bool Dijkastra() {
    for(int i = st; i <= sf; i++) taxa[i] = INF;
    memset(fr, false, sizeof(fr));
    queue<int> q;

    taxa[st] = 0;
    fr[st] = true;


    q.push(st);

    while(!q.empty()) {
        int nod = q.front();
        q.pop();

        fr[nod] = false;
        for(int urm : gr[nod]) {
            int costUrm = taxa[nod] + cost[nod][urm];
            if(costUrm < taxa[urm] && flux[nod][urm] > 0) {
                taxa[urm] = costUrm;
                tata[urm] = nod;

                if(!fr[urm]) {
                    fr[urm] = true;
                    q.push(urm);
                }
            }
        }
    }

    return taxa[sf] != INF;
}

static inline void BackTrack() {
    int cur = sf;
    int ma = INF;
    while(cur != st) {
        ma = min(ma, flux[tata[cur]][cur]);
        cur = tata[cur];
    }

    cur = sf;
    while(cur != st) {
        flux[tata[cur]][cur] -= ma;
        flux[cur][tata[cur]] += ma;
        cur = tata[cur];
    }
    rasp += taxa[sf] * ma;
}

int main() {
    if(ST_DIO) ios_base::sync_with_stdio(false);
    fin.tie(nullptr);
    fout.tie(nullptr);

    fin >> n;

    st = 0;
    sf = 2 * n + 1;

    for(i = 1; i <= n; i++) {
        for(j = 1; j <= n; j++) {
            int c;
            fin >> c;
            cost[i][j + n] =  c;
            cost[j + n][i] = -c;
            flux[i][j + n] = 1;
            gr[i].push_back(j + n);
            gr[j + n].push_back(i);
        }
    }

    for(i = 1; i <= n; i++) {
        gr[st].push_back(i);
        gr[i].push_back(st);
        gr[sf].push_back(i + n);
        gr[i + n].push_back(sf);
        flux[st][i] = 1;
        flux[i + n][sf] = 1;
    }

    while(Dijkastra())
        BackTrack();
    fout << rasp;

    return 0;
}