Cod sursa(job #578313)

Utilizator sodamngoodSo Damn Good sodamngood Data 11 aprilie 2011 10:45:46
Problema Cuplaj maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.6 kb
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
#define maxn 610
#define inf 99999999
#define pii pair<int, int>
#define pb push_back
#define mkp make_pair

int N, M, E, S, D, sol, nr;
int C[maxn][maxn], F[maxn][maxn], edge[maxn][maxn];
int dist[maxn], tt[maxn];
bool InQueue[maxn];
vector<pii> G[maxn];
vector<int> muchii;

int BellmanFord() {
    queue<int> Q;
    for(int i=S; i<=D; i++) {
         InQueue[i] = false;
         dist[i] = inf;
         tt[i] = 0;
    }
    dist[S] = 0;
    Q.push(S);
    InQueue[S] = true;
    while(!Q.empty()) {
         int nod = Q.front(); Q.pop();
         InQueue[nod] = false;
         for(vector<pii>::iterator it=G[nod].begin(); it!=G[nod].end(); it++) {
              if(C[nod][ (*it).first ] > F[nod][ (*it).first ] && dist[ (*it).first ] > dist[nod] + (*it).second) {
                   tt[ (*it).first ] = nod;
                   dist[ (*it).first ] = dist[nod] + (*it).second;
                   if(!InQueue[ (*it).first ]) {
                        InQueue[ (*it).first ] = true;
                        Q.push( (*it).first );
                   }
              }
         }
    }

    if(dist[D] != inf) {
         int flow = inf;
         for(int i=D; i!=S; i=tt[i]) {
              flow = min(flow, C[tt[i]][i] - F[tt[i]][i]);
         }
         for(int i=D; i!=S; i=tt[i]) {
              F[tt[i]][i] += flow;
              F[i][tt[i]] -= flow;
         }

         return dist[D] * flow;
    }
    else {
         return 0;
    }
}

int main() {
    FILE *f1=fopen("cmcm.in", "r"), *f2=fopen("cmcm.out", "w");
    int i, j, p, q, c;

    fscanf(f1, "%d %d %d\n", &N, &M, &E);
    for(i=1; i<=E; i++) {
         fscanf(f1, "%d %d %d\n", &p, &q, &c);
         G[p].pb( mkp(N + q, c) );
         G[N + q].pb( mkp(p, -c) );

         C[p][N + q] = 1; edge[p][N + q] = i;
    }
    for(i=1; i<=N; i++) {
         G[0].pb( mkp(i, 0) );
         G[i].pb( mkp(0, 0) );

         C[0][i] = 1;
    }
    for(i=N+1; i<=N+M; i++) {
         G[N+M+1].pb( mkp(i, 0) );
         G[i].pb( mkp(N+M+1, 0) );

         C[i][N+M+1] = 1;
    }

    S = 0, D = N + M + 1;

    int ok = BellmanFord();
    while(ok) {
         sol += ok;
         ok = BellmanFord();
    }

    for(i=1; i<=N; i++) {
         for(j=N+1; j<=N+M; j++) {
              if(C[i][j] && C[i][j] == F[i][j]) {
                   muchii.pb( edge[i][j] );
              }
         }
    }

    fprintf(f2, "%d %d\n", muchii.size(), sol);
    for(i=0; i<muchii.size(); i++) {
         fprintf(f2, "%d ", muchii[i]);
    } fprintf(f2, "\n");

    fclose(f1); fclose(f2);
    return 0;
}