Cod sursa(job #2562477)

Utilizator aZvezdaAtanas Dimitrov aZvezda Data 29 februarie 2020 14:51:48
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
struct Edge {
	int to, f, cap;
	Edge() {}
	Edge(int _to, int _f, int _cap) {to = _to; f = _f; cap = _cap;}
};

const int MAX_N = 1e4 + 10;

struct FlowNetwork {
	vector<Edge> edges; 
	vector<int> g[MAX_N];
	void add(int a, int b, int c) {
		cout << a << " " << b << " " << c << endl;
		g[a].push_back(edges.size());		
		edges.emplace_back(b, 0, c);
		g[b].push_back(edges.size());		
		edges.emplace_back(a, 0, 0);
	}
	int s, t;
	int pind[MAX_N], dist[MAX_N];
	bool bfs() {
		for(int i = 0; i < MAX_N; i ++) {dist[i] = mod; pind[i] = 0;}
		dist[s] = 0;
		queue<int> q; q.push(s);
		while(!q.empty()) {
			int curr = q.front(); q.pop();
			for(auto it : g[curr]) {
				if(edges[it].f < edges[it].cap && dist[edges[it].to] == mod) {
					dist[edges[it].to] = dist[curr] + 1;
					q.push(edges[it].to);
				}
			}
		}
		return dist[t] != mod;
		
	}
	int dfs(int x, int val) {
		if(x == t || val == 0) {return val;}
		for(; pind[x] < g[x].size();) {
			int curr = g[x][pind[x] ++];
			if(dist[x] + 1 != dist[edges[curr].to] || edges[curr].f >= edges[curr].cap) {continue;}
			int now = dfs(edges[curr].to, min(edges[curr].cap - edges[curr].f, val));
			if(now == 0) {continue;}
			edges[curr].f += now;
			edges[curr ^ 1].f -= now;
			return now;
		}
		return 0;
	}
	int maxFlow() {
		int ans = 0;
		while(true) {
			if(!bfs()) {return ans;}
			int now = 0;
			while(now = dfs(s, mod)) {
				ans += now;
			}
		}
		return ans;
	}
};

FlowNetwork fn;


int main() {
    ofstream myfile;
    myfile.open ("maxflow.out");
    ifstream myFileIn;
    myFileIn.open ("maxflow.in");
    ll n, m;
    myFileIn >> n >> m;
    Dinic dc(1, n, n + 1);
    for(ll i = 0; i < m; i ++) {
        ll a, b, cap;
        myFileIn >> a >> b >> cap;
        dc.addEdge(a, b, cap);
    }	
    myfile << dc.maxFlow() << endl;
}