Cod sursa(job #1721327)

Utilizator cristina_borzaCristina Borza cristina_borza Data 25 iunie 2016 12:29:10
Problema Tribut Scor 100
Compilator cpp Status done
Runda Arhiva ICPC Marime 2.52 kb
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>

#define INF 10000005

using namespace std;

ifstream f("tribut.in");
ofstream g("tribut.out");

int c[500][500] , flow[500][500] , t[500];
int T , n , m , flux , mx , nr , x;

vector <vector <int> > G;

bool bfs();

int main() {
    f >> T;
    while (T--) {
        f >> n >> m;

        G.clear();
        G.resize(n + m + 5);

        memset(flow , 0 , sizeof(flow));
        memset(c , 0 , sizeof(c));
        memset(t , 0 , sizeof(t));

        flux = 0;

        for (int i = 1; i <= n; ++i) {
            f >> x;

            c[1][i + 1] = x;
            G[1].push_back(i + 1);
            G[i + 1].push_back(i);
        }

        for (int i = 1; i <= m; ++i) {
            f >> nr >> mx;

            c[n + 1 + i][n + m + 2] = mx;
            G[n + 1 + i].push_back(n + m + 2);
            G[n + m + 2].push_back(n + 1 + i);

            for (int j = 1; j <= nr; ++j) {
                f >> x;

                c[x + 1][n + 1 + i] = INF;
                G[x + 1].push_back(n + 1 + i);
                G[n + 1 + i].push_back(x + 1);
            }
        }

        while (bfs()) {
            for (vector <int> :: iterator it = G[n + m + 2].begin(); it != G[n + m + 2].end(); ++it) {
                if (flow[*it][n + m + 2] < c[*it][n + m + 2] && t[*it]) {
                    int u = *it , val = c[*it][n + m + 2] - flow[*it][n + m + 2];
                    while (u != 1) {
                        val = min(val , c[t[u]][u] - flow[t[u]][u]);
                        u = t[u];
                    }

                    u = *it;
                    flow[*it][n + m + 2] += val;
                    flow[n + m + 2][*it] -= val;

                    while (u != 1) {
                        flow[t[u]][u] += val;
                        flow[u][t[u]] -= val;
                        u = t[u];
                    }

                    flux += val;
                }
            }
        }

        g << flux << '\n';
    }
    return 0;
}


bool bfs() {
    queue <int> q;
    q.push(1);

    memset(t , 0 , sizeof(t));
    t[1] = -1;

    while (!q.empty()) {
        int node = q.front();
        for (vector <int> :: iterator  it = G[node].begin(); it != G[node].end(); ++it) {
            if (flow[node][*it] < c[node][*it] && !t[*it]) {
                q.push(*it);
                t[*it] = node;
            }
        }

        q.pop();
    }

    return (t[n + m + 2] != 0);
}