FASTFLOW - Fast Maximum Flow


Given a graph with N (2 ≤ N ≤ 5,000) vertices numbered 1 to N and M (1 ≤ M ≤ 30,000) undirected, weighted edges, compute the maximum flow / minimum cut from vertex 1 to vertex N.

Input

The first line contains the two integers N and M. The next M lines each contain three integers A, B, and C, denoting that there is an edge of capacity C (1 ≤ C ≤ 109) between nodes A and B (1 ≤ A, B ≤ N). Note that it is possible for there to be duplicate edges, as well as an edge from a node to itself.

Output

Print a single integer (which may not fit into a 32-bit integer) denoting the maximum flow / minimum cut between 1 and N.

Example

Input:
4 6
1 2 3
2 3 4
3 1 2
2 2 5
3 4 3
4 3 3

Output:
5

Viewing the problem as max-flow, we may send 3 units of flow through the path 1 - 2 - 3 - 4 and 2 units of flow through the path 1 - 3 - 4. Viewing the problem as min-cut, we may cut the first and third edges. Either way the total is 5.

Note: see also http://www.spoj.com/problems/MATCHING/.


hide comments
sigma_poet: 2016-01-10 05:57:59

Dinic 's time is O(N^2*M), but N is 5000 and M is 30000. Will it get a pass ??? I'm not sure.

Dario Pavlovic: 2015-07-30 17:04:32

yup, a well written dinic works.

dfranzen: 2015-07-14 01:01:59

dinic's algorithm works ;)

Last edit: 2015-07-14 01:09:48
(Tjandra Satria Gunawan)(曾毅昆): 2015-05-28 16:35:09

very fun! among 931 accepted users (for now), only 10 of them using pure C language ;-)

dened: 2015-01-22 09:17:23

My solution using highest-label push-relabel algorithm was accepted even without any heuristics. But I had to implement an efficient data structure for the sparse graph.

Reza: 2014-12-23 13:41:26

Dinic --> Accepted. trust me :-"

Anuj Arora: 2014-11-30 20:54:09

Very hard problem.......too many TLE......phewww

Luis Manuel D�az Bar�n: 2014-08-12 16:39:25

Edmonds-Karp TLE on test 11. It should be allowed to pass

Last edit: 2014-08-25 17:34:51
rahul kumar: 2014-08-07 20:56:07

can anybody tell me why im getting WA on 12th test

Anmol Pandey: 2014-07-15 13:37:33

Edmond-Karps algo gives TLE

Last edit: 2014-07-15 13:38:40

Added by:Neal Wu
Date:2009-03-25
Time limit:2s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ERL JS-RHINO