Cod sursa(job #1739638)

Utilizator CiurezAndreiCiurez Marius-Andrei CiurezAndrei Data 9 august 2016 22:11:31
Problema Tribut Scor 0
Compilator cpp Status done
Runda Arhiva ICPC Marime 2.54 kb
#include <bits/stdc++.h>

#define S 0
#define INF 1000000000
#define D N + M + 1

using namespace std;

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

int N, M, C[128][128], F[128][128], solution, t[128], T, P, cap, x, flux;
vector <int> L[128];
queue  <int> Q;
bool v[128];

bool BFS()
{
    memset(v, 0, sizeof(v));

    Q.push(S);

    while( !Q.empty() )
    {
        int node = Q.front();
        Q.pop();

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

            if( v[neighbour] == false && C[node][neighbour] > F[node][neighbour] )
            {
                Q.push(neighbour);
                v[neighbour] = true;
                t[neighbour] = node;
            }
        }
    }

    return v[D];

}

int main()
{
    fin >> T;

    while(T --)
    {
        fin >> N >> M;

        memset(C, 0, sizeof(C));
        memset(F, 0, sizeof(F));
        memset(t, 0, sizeof(t));

        solution = 0;

        for(int i = 0; i <= 126; i ++)
        {
            L[i].clear();
        }

        for(int i = 1; i <= N; i ++)
        {
            fin >> C[S][i];
            L[S].push_back(i);
            L[i].push_back(S);
        }

        for(int i = 1; i <= M; i ++)
        {
            fin >> P;
            fin >> cap;

            L[D].push_back(N + i);
            L[N + i].push_back(D);
            C[N + i][D] = cap;

            for(int j = 1; j <= P; j ++)
            {
                fin >> x;
                L[N + i].push_back(x);
                L[x].push_back(N + i);
                C[x][N + i] = INF;
            }
        }

        while( BFS() )
        {
            for(int i = 0; i < L[D].size(); i ++)
            {
               x = L[D][i];

               flux = C[x][D] - F[x][D];

               if(v[x] == true)
               {
                   while(x > S)
                   {
                       flux = min(flux, C[ t[x] ][x] - F[ t[x] ][x]);
                       x = t[x];
                   }

                   x = L[D][i];

                   F[x][D] += flux;
                   F[D][x] -= flux;

                   while(x > S)
                   {
                       F[ t[x] ][x] += flux;
                       F[x][ t[x] ] -= flux;
                       x = t[x];
                   }

                   solution += flux;
               }

            }
        }
        fout << solution << "\n";
    }





    return 0;
}