Cod sursa(job #1517197)

Utilizator CiurezAndreiCiurez Marius-Andrei CiurezAndrei Data 3 noiembrie 2015 22:42:24
Problema Cuplaj maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.82 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <limits.h>
#include <queue>

#define DIM 639
#define INF INT_MAX

using namespace std;

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

int N, M, beginning, ending, x, y, cap, c, minimum, solution, d, E;
int capacity[DIM][DIM], flow[DIM][DIM], cost[DIM][DIM];
int T[DIM], D[DIM], muchii[DIM][DIM], flux;

vector<int>L[DIM];
bitset<DIM>V;
queue<int>q;

int bellman_ford()
{
    for(int i = 1; i <= d; i ++)
    {
        D[i] = INF;
        V[i] = 0;
    }
    D[0] = 0;
    q.push(0);

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

        for(int i = 0; i < L[ node ].size(); i ++)
        {
            int neighbour = L[ node ][i];

            if( (D[neighbour] > D[ node ] + cost[ node ][neighbour]) && (flow[ node ][neighbour] < capacity[ node ][neighbour] ) )
            {
                D[neighbour] = D[ node ] + cost[ node ][neighbour];
                T[ neighbour ] = node;

                if(V[neighbour] == 0)
                {
                    q.push(neighbour);
                    V[neighbour] = 1;
                }
            }
        }
    }

    if(D[d] != INF)
    {
        return 1;
    }

    return 0;
}


int main()
{
    fin >> N >> M >> E;

    for(int i = 1; i <= E; i ++)
    {
        fin >> x >> y >> c;
        L[x].push_back(N + y);
        L[N + y].push_back(x);

        capacity[x][N + y] = 1;
        cost[x][N + y] = c;
        cost[N + y][x] = -c;
        muchii[x][N + y] = i;
    }

    for(int i = 1; i <= N; i ++)
    {
        capacity[0][i] = 1;
        cost[0][i] = cost [i][0] = 0;
        L[0].push_back(i);
        L[i].push_back(0);
    }

    d = N + M + 1;

    for(int i = 1; i <= M; i ++)
    {
        capacity[N + i][d] = 1;
        cost[N +i][d] = cost[d][N + 1] = 0;
        L[N + i].push_back(d);
        L[d].push_back(N + i);
    }

    while(bellman_ford())
    {
        minimum = INF;
        int x = d;

        while(x != 0)
        {
            if(minimum > capacity[ T[x] ][x] - flow[ T[x] ][x]  )
            {
                minimum = capacity[ T[x] ][x] - flow[ T[x] ][x];
            }

            x = T[x];
        }

        x = d;

        while(x != 0)
        {
            solution += minimum * cost[ T[x] ][x];
            flow[ T[x] ][x] += minimum;
            flow[x][ T[x] ] -= minimum;

            x = T[x];
        }
        flux += minimum;
    }

    fout << flux << " " << solution << '\n';

    for(int i = 1; i <= N; i ++)
    {
        for(int j = N + 1; j <= N + M; j ++)
        {
            if(flow[i][j] == 1)
            {
                fout << muchii[i][j] << " ";
            }
        }
    }

    return 0;
}