Cod sursa(job #1790776)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 28 octombrie 2016 18:23:49
Problema Flux maxim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.33 kb
#include <bits/stdc++.h>

using namespace std;

#define start 1
#define dest N

struct Edge{
    int from;
    int to;
    int flow;
    int capacity;
    Edge(){
        from = to = flow = capacity = 0;
    }
    Edge(int f, int t, int fl, int capac) {
        this->from = f;
        this->to = t;
        this->flow = fl;
        this->capacity = capac;
    }
};

const int Nmax = 1005;
vector<Edge> edges;
vector<vector<pair<int,int> > > G;
bitset<Nmax> used;
queue<int> Q;

int N, M, daddy[Nmax];

void insertEdge(int from, int to, int flow, int capacity)
{
    int crt = 0;
    edges.emplace_back(from, to, flow, capacity);
    crt = edges.size() - 1;
    G[from].emplace_back(to, crt);

    edges.emplace_back(to, from, 0, 0);
    crt = edges.size() - 1;
    G[to].emplace_back(from, crt);
}

void readNetwork()
{
    cin >> N >> M;
    G.resize(N+1);

    for(int i = 1; i <= M; ++i) {
        int a,b,c;
        cin >> a >> b >> c;
        insertEdge(a,b,0,c);
    }
}

bool BFS(int k)
{
    used = 0;
    memset(daddy, 0, sizeof(daddy));
    used[k] = true;
    Q.push(k);
    while(!Q.empty()) {
        k = Q.front(); Q.pop();
        for(auto it : G[k])
            if(!used[it.first] && edges[it.second].capacity > edges[it.second].flow)
            {
                used[it.first] = true;
                Q.push(it.first);
                daddy[it.first] = it.second;
            }
    }
    return used[dest];
}

int maxFlow(int k)
{
    const int INF = 0x3f3f3f3f;
    int maxFlow = 0;

    while(BFS(k))
    for(auto it : G[dest])
    {
        if(!used[it.first] || edges[it.second^1].capacity == edges[it.second^1].flow)
            continue;
        daddy[dest] = it.second ^ 1;

        int crt = INF;
        for(int node = dest; node != start; node = edges[daddy[node]].from)
            crt = min(crt, edges[daddy[node]].capacity - edges[daddy[node]].flow);
        for(int node = dest; node != start; node = edges[daddy[node]].from)
        {
            edges[daddy[node]].flow += crt;
            edges[daddy[node]^1].flow -= crt;
        }
        maxFlow += crt;
    }
    return maxFlow;
}

int main()
{
    freopen("maxflow.in","r",stdin);
    freopen("maxflow.out","w",stdout);

    readNetwork();
    cout << maxFlow(start);

    return 0;
}