Cod sursa(job #1166271)

Utilizator Dddarius95Darius-Florentin Neatu Dddarius95 Data 3 aprilie 2014 13:39:45
Problema Cuplaj maxim de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#define pb push_back
#define oo 2000000000
using namespace std;
ifstream f("cmcm.in");
ofstream g("cmcm.out");

int L,R,z, N, M, D[610], cap[610][610], flux[610][610], prec[610], cost[610][610], used[610], x, y, c, maxflow, source, sink, costmin,cuplate,st[610],nr[610][610];
vector <int> G[610],sol;
queue < int > Q;
bool inQ[610];

inline int bellman(int sursa)
{
    for (int i=0; i<=N; ++i)
        D[i]=prec[i]=oo, used[i]=inQ[i]=0;
    Q.push(sursa); inQ[sursa]=1; D[sursa]=0; prec[sursa]=sursa;
    while (Q.size())
    {
        int nod=Q.front(); Q.pop(); ++used[nod]; inQ[nod]=0;
        if (used[nod]==N) return 0;
        vector <int>::iterator it=G[nod].begin();
        for (; it!=G[nod].end(); ++it)
            if (D[*it]>D[nod]+cost[nod][*it] && cap[nod][*it]>flux[nod][*it])
            {
                D[*it]=D[nod]+cost[nod][*it]; prec[*it]=nod;
                if (!inQ[*it]) Q.push(*it), inQ[*it]=1;
            }
    }
    return (D[sink]!=oo);
}

void minflow(int sursa, int sink)
{
    for (; bellman(sursa); )
    {
        for (int x=sink; x!=sursa; x=prec[x])

                {
                    ++flux[prec[x]][x],
                    --flux[x][prec[x]];

                    if(flux[prec[x]][x]>0)st[prec[x]]=x;
                        else if(flux[prec[x]][x]==0)st[prec[x]]=0;
                }
        costmin+=D[sink];
    }
}

int main()
{
    f>>L>>R>>M;
    N=L+R+1;
    for (int i=1; i<=M; ++i)
    {
        f>>x>>y>>c;
        y+=L;
        cap[x][y]=1; G[x].pb(y);
        cost[x][y]=c; cost[y][x]=-c; G[y].pb(x);
        nr[x][y]=i;

        G[0].pb(x) , G[x].pb(0);
        cap[0][x]=1;

        G[y].pb(N) , G[N].pb(y);
        cap[y][N]=1;
    }

    source=0, sink=N;
    minflow(0, N);

    for(int i=1;i<=L;++i)
        if(st[i])
        {
            ++cuplate;
            sol.pb(nr[i][st[i]]);
        }


    g<<cuplate<<' '<<costmin<<'\n';
    for(int i=0;i<cuplate;++i)g<<sol[i]<<' ';
    g<<'\n';
    return 0;
}