Cod sursa(job #1959031)

Utilizator razvandRazvan Dumitru razvand Data 9 aprilie 2017 00:18:43
Problema Cuplaj maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.47 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <climits>

using namespace std;

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

int cst[2*303][2*303];
int flw[2*303][2*303];
vector<int> e[2*303];
vector<int> num[2*303];
int N;
int bst[2*303];
int bef[2*303];
bitset<2*303> inq;

bool bellman() {

    for(int i = 0; i <= N; i++)
        bst[i] = 20000*50000+1;

    queue<int> Q;
    bst[0] = 0;
    Q.push(0);
    inq[0] = true;
    int nod;
    int nx;

    while(!Q.empty()) {
        nod = Q.front();
        Q.pop();
        inq[nod] = false;
        for(int i = 0; i < e[nod].size(); i++) {
            nx = e[nod][i];
            if(flw[nod][nx] == 0)
                continue;
            if(bst[nx] > bst[nod] + cst[nod][nx]) {
                bst[nx] = bst[nod] + cst[nod][nx];
                bef[nx] = nod;
                if(!inq[nx])
                    Q.push(nx);
            }
        }
    }

    if(bst[N] != 20000*50000+1)
        return true;
    return false;

}

int main() {

    int n,m,E;
    in >> n >> m >> E;
    int x,y,z;
    N = n+m+1;

    for(int i = 1; i <= E; i++) {
        in >> x >> y >> z;
        cst[x][n+y] = z;
        cst[n+y][x] = -z;
        flw[x][n+y] = 1;
        e[x].push_back(n+y);
        num[x].push_back(i);
        e[n+y].push_back(x);
    }

    for(int i = 1; i <= n; i++) {
        flw[0][i] = 1;
        e[0].push_back(i);
        e[i].push_back(0);
    }

    for(int i = 1; i <= m; i++) {
        flw[n+i][N] = 1;
        e[n+i].push_back(N);
        e[N].push_back(n+i);
    }

    int flm = INT_MAX/2;
    int tot = 0;
    int w = 0;

    while(bellman()) {

        int crr = N;
        flm = INT_MAX/2;

        while(crr != 0) {
            flm = min(flm, flw[bef[crr]][crr]);
            crr = bef[crr];
        }

        tot += bst[N]*flm;
        crr = N;

        while(crr != 0) {
            flw[bef[crr]][crr] -= flm;
            flw[crr][bef[crr]] += flm;
            crr = bef[crr];
        }

        w++;

    }

    out << w << " " << tot << '\n';
    int nx;

    for(int i = 1; i <= n; i++) {
        for(int j = 0; j < e[i].size(); j++) {
            nx = e[i][j];
            if(nx == 0)
                continue;
            if(flw[i][nx] == 0) {
                out << num[i][j] << " ";
                break;
            }
        }
    }

    return 0;
}