Cod sursa(job #2877962)

Utilizator NanuGrancea Alexandru Nanu Data 25 martie 2022 17:30:39
Problema Cuplaj maxim de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

#define DIM 605
#define INF (1LL << 30)

int n, m, e;
bool sel[DIM + 1];
int d[DIM + 1], fr[DIM + 1], t[DIM + 1];
int C[DIM + 1][DIM + 1], F[DIM + 1][DIM + 1];
vector <int > G[DIM + 1];

static inline bool Bellman_Ford(int S, int D) {
    for(int i = 1; i <= n; i++) {
        d[i] = INF;
        fr[i] = 0;
        t[i] = 0;
    }
    d[S] = 0;

    queue<int> Q;
    Q.push(S);
    sel[S] = 1;
    while(!Q.empty()) {
        int nod = Q.front();
        sel[nod] = 0;
        Q.pop();

        fr[nod]++;
        if(fr[nod] == n)
            return 0;

        for(auto e : G[nod])
            if(d[e] > d[nod] + C[nod][e] && C[nod][e] > F[nod][e]) {
                d[e] = d[nod] + C[nod][e];
                t[e] = nod;
                if(!sel[e]) {
                    sel[e] = 1;
                    Q.push(e);
                }
            }
    }
    return (d[D] != INF);
}

int main()
{
    fin >> n >> m >> e;
    for(int i = 1; i <= e; i++) {
        int x, y, c;

        fin >> x >> y >> c;
        y += n;

        G[x].push_back(y);
        G[y].push_back(x);

        C[x][y] = c;
        C[y][x] = -c;
    }

    int S = 0;  ///sursa
    int D = n + m + 1;  ///destinatia;
    for(int i = 1; i <= n; i++) {
        G[S].push_back(i);
        G[i].push_back(S);
        ///C[S][i] = 1;
    }

    for(int i = n + 1; i <= n + m; i++) {
        G[i].push_back(D);
        G[D].push_back(i);
    }

    int maxflow = 0;
    while(Bellman_Ford(S, D)) {
        int nod = D;
        int minim = INF;
        while(nod != S) {
            minim = min(minim, C[t[nod]][nod] - F[t[nod]][nod]);
            nod = t[nod];
        }

        nod = D;
        while(nod != D) {
            F[t[nod]][nod] += minim;
            F[nod][t[nod]] -= minim;
            nod = t[nod];
        }
        maxflow += minim;
    }

    fout << maxflow << " ";

    return 0;
}