Cod sursa(job #3186043)

Utilizator AntoniaPopoviciAntonia-Adelina Popovici AntoniaPopovici Data 21 decembrie 2023 09:43:42
Problema Cc Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.94 kb
#include <fstream>
#include <queue>
#include <algorithm>

using namespace std;

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

const int INF = 1e9;
const int N_MAX = 300;

int tata[N_MAX], graf[N_MAX][N_MAX], cost[N_MAX][N_MAX], v[N_MAX], S = 1, D, NMAX;

struct elem {
    int cost, tata, nod;
    elem(int _cost, int _nod, int _tata) : nod(_nod), cost(_cost), tata(_tata) {}
};

bool cmp(const elem& x, const elem& y) {
    return x.cost > y.cost;
}


bool dijkstra() {
    priority_queue<elem, vector<elem>, decltype(&cmp)> q(cmp);
    fill(v, v + N_MAX, INF);

    q.push(elem(0, S, -1));
    v[S] = 0;

    while (!q.empty()) {
        elem nod_vf = q.top();
        q.pop();

        int c = nod_vf.cost;
        int nod = nod_vf.nod;
        int t = nod_vf.tata;

        if (c > v[nod]) continue;

        tata[nod] = t;

        if (nod == D) return true;

        for (int i = 0; i <= NMAX; i++) {
            int cc = c + cost[nod][i];
            if (graf[nod][i] > 0 && cc < v[i]) {
                v[i] = cc;
                q.push(elem(cc, i, nod));
            }
        }
    }

    return false;
}


int main() {
    int m;
    int rez = 0;

    fin >> m;
    
    D = 2 * m + 2;

    for (int i = 2; i <= m + 1; i++) {
        graf[1][i] = graf[i + m][2 * m + 2] = 1;
    }

    for (int i = 2; i < m + 2; i++) {
        for (int j = m + 2; j < 2 * m + 2; j++) {
            fin >> cost[i][j];
            cost[j][i] = -cost[i][j];
            graf[i][j] = 1;
        }
    }

    while (dijkstra()) {
        for (int i = D; tata[i] != -1; i = tata[i]) {
            graf[tata[i]][i] -= 1;
            graf[i][tata[i]] += 1;
        }
    }

    for (int i = 2; i < m + 2; i++) {
        for (int j = m + 2; j < 2 * m + 2; j++) {
            if (graf[i][j] == 0) {
                rez += cost[i][j];
            }
        }
    }

    fout << rez;

    return 0;
}