Cod sursa(job #2293367)

Utilizator felixiPuscasu Felix felixi Data 30 noiembrie 2018 22:10:35
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1000;
const int DMAX = 1e6;

struct MaxFlowDinic
{
    struct Edge
    {
		int flow, to, next;
	};

	vector<Edge> edges;
	vector<int> adia, where, dist;

	MaxFlowDinic(int n) {
		where = dist = adia = vector<int>(n + 1, -1);
	}

	void addEdge(int x, int y, int c)
	{
		edges.push_back({c, y, adia[x]});
		adia[x] = edges.size() - 1;

		edges.push_back({0, x, adia[y]});
		adia[y] = edges.size() - 1;
	}

	bool bfs(int s, int d) {
		fill(dist.begin(), dist.end(), -1);
		dist[s] = 0;
		queue<int> q;
		q.push(s);
		while( !q.empty() ) {
			int x = q.front();
			q.pop();
			for( int i = adia[x];  i != -1;  i = edges[i].next ) {
				if( dist[edges[i].to] == -1 && edges[i].flow ) {
					dist[edges[i].to] = 1 + dist[x];
					q.push(edges[i].to);
				}
			}
		}
		return dist[d] != -1;
	}

	int dfs(int nod, int d, int fmax = DMAX)
	{
		if (nod == d)
			return fmax;

		while ( where[nod] != -1 ) {
			Edge& e = edges[where[nod]];
			int nf = min(fmax, e.flow);
			if (dist[e.to] == dist[nod] + 1 && e.flow && (nf = dfs(e.to, d, nf))) {
				e.flow -= nf;
				edges[where[nod] ^ 1].flow += nf;
				return nf;
			}
			where[nod] = edges[ where[nod] ].next;
		}
		return 0;
	}

	int calcFlow(int s, int d) {
		int debit = 0;
		while( bfs(s, d) ) {
			where = adia;
			while( int added = dfs(s, d) )
				debit += added;
		}
		return debit;
	}
};

ifstream in("maxflow.in");
ofstream out("maxflow.out");

int main()
{
    int N, M;
    in >> N >> M;
    MaxFlowDinic MFD(N);
    for( int i =1;  i <= M;  ++i ) {
        int x,y,c;
        in >> x >> y >> c;
        MFD.addEdge(x, y, c);
    }
    out << MFD.calcFlow(1, N) << '\n';
    return 0;
}