Cod sursa(job #1980614)

Utilizator gabib97Gabriel Boroghina gabib97 Data 13 mai 2017 15:38:24
Problema Cuplaj maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <bits/stdc++.h>

#define N 305
#define pp pair<int,int>
using namespace std;
int n, m, C[2 * N][2 * N];
int t[2 * N], e, flow, u, w, E[N][2 * N], cE[N][2 * N], cost, d[2 * N], p[2*N];
const int inf = numeric_limits<int>::max();
bool o[2 * N];
vector<pp > G[2 * N];
vector<int> r;
queue<int> Q;

bool bellman_ford()
{
    int i, s, x;
    t[0] = -1;
    for (i = 1; i <= u; i++) d[i] = inf, t[i] = -1;
    memset(o, 0, sizeof(o));
    Q.push(0);
    o[0] = 1;

    while (!Q.empty()) {
        s = Q.front();
        Q.pop();
        o[s] = 0;

        for (i = 0; i < G[s].size(); i++) {
            x = G[s][i].first;
            if (C[s][x] > 0 && d[x] > d[s] + G[s][i].second) {
                d[x] = d[s] + G[s][i].second;
                t[x] = s;
                if (!o[x])
                    Q.push(x), o[x] = 1;
            }
        }
    }
    return t[u] != -1;
}

int main()
{
    freopen("cmcm.in", "r", stdin);
    freopen("cmcm.out", "w", stdout);

    int i, x, y, c;
    scanf("%i%i%i", &n, &m, &e);
    u = n + m + 1;

    for (i = 1; i <= e; i++) {
        scanf("%i%i%i", &x, &y, &c);
        G[x].push_back(make_pair(y + n, c));
        G[y + n].push_back(make_pair(x, -c));
        C[x][y + n] = 1;
        E[x][y + n] = i;
        cE[x][y + n] = c;
    }

    for (i = 1; i <= n; i++) {
        G[0].push_back(make_pair(i, 0)); // from source
        G[i].push_back(make_pair(0, 0));
        C[0][i] = 1;
    }
    for (i = 1; i <= m; i++) {
        G[i + n].push_back(make_pair(u, 0)); // to dest
        G[u].push_back(make_pair(i + n, 0));
        C[i + n][u] = 1;
    }

    while (bellman_ford()) {
        w = inf;
        for (i = u; i > 0; i = t[i])
            w = min(w, C[t[i]][i]);

        flow += w;

        for (i = u; i > 0; i = t[i]) {
            p[t[i]] = i;
            C[t[i]][i] -= w;
            C[i][t[i]] += w;
        }
    }

    for (i = 1; i <= n; i++)
        if (p[i]) cost += cE[i][p[i]], r.push_back(E[i][p[i]]);
    printf("%i %i\n", flow, cost);
    for (i = 0; i < r.size(); i++)
        printf("%i ", r[i]);
    return 0;
}