Cod sursa(job #1503097)

Utilizator stefanzzzStefan Popa stefanzzz Data 15 octombrie 2015 16:09:08
Problema Cuplaj maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.22 kb
#include <stdio.h>
#include <queue>
#include <vector>
#include <assert.h>
#include <string.h>
#define MAXN 700
#define INF 0x3fffffff
#define MIN(a, b) (((a) < (b))?(a):(b))
using namespace std;

int n, m, e, fx[MAXN][MAXN], cap[MAXN][MAXN], cost[MAXN][MAXN], ind[MAXN][MAXN];
int start, fin, dist[MAXN], bk[MAXN], x, y, c;
bool uzq[MAXN];
vector<int> G[MAXN];

bool BelmanFord() {
    for(int i = 1; i <= n + m + 2; i++) {
        dist[i] = INF;
        bk[i] = uzq[i] = 0;
    }

    dist[start] = 0;

    queue<int> q;
    q.push(start), uzq[start] = 1;

    while(!q.empty()) {
        int x = q.front();
        q.pop(), uzq[x] = 0;

        for(auto y: G[x]) {
            if(fx[x][y] < cap[x][y] && dist[x] + cost[x][y] < dist[y]) {
                dist[y] = dist[x] + cost[x][y];
                bk[y] = x;
                if(!uzq[y]) q.push(y), uzq[y] = 1;
            }
        }
    }

    return bk[fin];
}

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

    scanf("%d %d %d", &n, &m, &e);
    for(int i = 1; i <= e; i++) {
        scanf("%d %d %d", &x, &y, &c);
        G[x].push_back(y + n);
        G[y + n].push_back(x);
        assert(!ind[x][y + n]);
        ind[x][y + n] = i;

        cap[x][y + n] = 1;
        cost[x][y + n] = c;
        cost[y + n][x] = -c;
    }

    start = n + m + 1, fin = n + m + 2;

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

    while(BelmanFord()) {
        int x = fin;
        while(x != start) {
            ++fx[bk[x]][x];
            --fx[x][bk[x]];
            x = bk[x];
        }
    }

    int totCost = 0;
    vector<int> sol;
    for(int i = 1; i <= n; i++)
        for(int j = n + 1; j <= n + m; j++)
            if(fx[i][j]) {
                sol.push_back(ind[i][j]);
                totCost += cost[i][j];
            }

    printf("%d %d\n", (int) sol.size(), totCost);
    for(auto x: sol)
        printf("%d ", x);
    printf("\n");

    return 0;
}