Cod sursa(job #3187637)

Utilizator alexandramocanu181Mocanu Alexandra alexandramocanu181 Data 29 decembrie 2023 19:39:08
Problema Cc Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.19 kb
// https: // www.infoarena.ro/problema/cc

#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#include <bitset>

using namespace std;

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

const int NMAX = 103;
const int DMAX = 2 * NMAX;
const int P = 1e2;
const int INF = 1e9;

vector<int> neighbors[DMAX];

int cost[DMAX][DMAX], cap[DMAX][DMAX], t[2 * NMAX], flow[DMAX][DMAX];

int n, sink, finished, ans, out;

bitset<DMAX> inq;

void BellmanFord()
{
    vector<int> dist(DMAX, INF);
    memset(t, 0, sizeof(t));
    dist[0] = 0;

    queue<int> q;
    inq.reset();
    q.push(0);

    while (!q.empty())
    {
        int v = q.front();
        q.pop();
        inq[v] = 0;

        for (auto neighbor : neighbors[v])
        {
            if ((cap[v][neighbor] - flow[v][neighbor]) == 0)
                continue;
            if (dist[v] + cost[v][neighbor] < dist[neighbor])
            {
                t[neighbor] = v;
                dist[neighbor] = dist[v] + cost[v][neighbor];
                if (!inq[neighbor])
                    q.push(neighbor);
            }
        }
    }

    if (dist[sink] == INF)
    {
        finished = 1;
        return;
    }

    for (int c = sink; c != 0; c = t[c])
    {
        flow[t[c]][c] += 1;
        flow[c][t[c]] -= 1;
    }

    ans += dist[sink];
}

void FordFulkerson()
{
    while (!finished)
        BellmanFord();

    fout << ans;
    exit(0);
}

int main()
{
    int n;
    fin >> n;
    sink = 2 * NMAX - 1;

    for (int i = 1; i <= n; i++)
    {
        for (int s = 1; s <= n; s++)
        {
            fin >> cost[i][s + P];
            cap[i][s + P] = 1;
            cap[s + P][sink] = 1;
            cost[s + P][i] = -cost[i][s + P];
            neighbors[s + P].emplace_back(i);
            neighbors[i].emplace_back(s + P);
        }
    }

    for (int i = 1; i <= n; i++)
    {
        neighbors[0].emplace_back(i);
        cap[0][i] = 1;
        neighbors[i + P].emplace_back(sink);
        neighbors[i].emplace_back(0);
        neighbors[sink].emplace_back(i + P);
    }

    FordFulkerson();

    return 0;
}