Cod sursa(job #2889749)

Utilizator mateitudordmDumitru Matei mateitudordm Data 13 aprilie 2022 10:47:22
Problema Cc Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.05 kb
#include <fstream>
#include <vector>
#include <queue>
#define nmax 300

using namespace std;

ifstream cin ("cc.in");
ofstream cout ("cc.out");

const int inf = 1e6;
int n, inq[nmax + 1], bst[nmax + 1], cost[nmax + 1][nmax + 1], flux[nmax + 1][nmax + 1], cap[nmax + 1][nmax + 1], prv[nmax + 1];
vector<int> ad[nmax + 1];
queue<pair<int, int>> q;
int bf()
{
    int a, c, i;
    for (i = 1; i <= 2 * n + 2; i++)
        inq[i] = prv[i] = 0, bst[i] = inf;
    q.push ({1, 0}), inq[1] = 1, bst[1] = 0;
    while (!q.empty())
    {
        a = q.front().first, c = bst[a], q.pop();
        inq[a] = 0;
        for (auto b : ad[a])
            if (cap[a][b] - flux[a][b] > 0 && c + cost[a][b] < bst[b])
            {
                bst[b] = c + cost[a][b], prv[b] = a;
                if (inq[b] == 0)
                    inq[b] = 1, q.push ({b, bst[b]});
            }
    }
    return (bst[2 * n + 2] != inf);
}

int main()
{
    int i, j, c, ult, a, actf, totcost = 0;
    cin >> n;
    for (i = 1; i <= n; i++)
        for (j = 1; j <= n; j++)
        {
            cin >> c;
            ad[i + 1].push_back (j + n + 1);
            ad[j + n + 1].push_back (i + 1);
            cost[i + 1][j + n + 1] = c;
            cost[j + n + 1][i + 1] = -c;
            cap[i + 1][j + n + 1] = inf;
        }
    for (i = 2; i <= n + 1; i++)
    {
        cap[1][i] = 1, cap[i + n][2 * n + 2] = 1;
        ad[1].push_back (i);
        ad[i].push_back (1);
        ad[i + n].push_back (2 * n + 2);
        ad[2 * n + 2].push_back (i + n);
    }
    while (bf())
    {
        ult = 2 * n + 2, a = prv[ult], actf = inf + 1;
        if (cap[a][ult] - flux[a][ult] > 0)
        {
            for (i = ult; i != 1; i = prv[i])
                actf  = min (actf, cap[prv[i]][i] - flux[prv[i]][i]);
            for (i = ult; i != 1; i = prv[i])
            {
                flux[prv[i]][i] += actf;
                flux[i][prv[i]] -= actf;
            }
            totcost += bst[ult];
        }
    }
    cout << totcost;
    return 0;
}