Set the default amount
int amt = INF ; for ( int x = sink ; x != src ; x = dad [ x ] ) amt = Math . min ( amt , flow [ x ] [ dad [ x ] ] != 0 ? flow [ x ] [ dad [ x ] ] : cap [ dad [ x ] ] [ x ] - flow [ dad [ x ] ] [ x ] ) ; for ( int x = sink ; x != src ; x = dad [ x ] ) { if ( flow [ x ] [ dad [ x ] ] != 0 ) { flow [ x ] [ dad [ x ] ] -= amt ; totcost -= amt * cost [ x ] [ dad [ x ] ] ; } else { flow [ dad [ x ] ] [ x ] += amt ; totcost += amt * cost [ dad [ x ] ] [ x ] ; } } totflow += amt ; }