Pagini recente » Cod sursa (job #1153054) | Cod sursa (job #1030296) | Cod sursa (job #1204874) | Cod sursa (job #60376) | Cod sursa (job #1893913)
#include <bits/stdc++.h>
using namespace std;
class InParser {
private:
FILE *fin;
char *buff;
int sp;
char read_ch() {
++sp;
if (sp == 4096) {
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume) {
fin = fopen(nume, "r");
buff = new char[4096]();
sp = 4095;
}
InParser& operator >> (int &n) {
char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
InParser& operator >> (long long &n) {
char c;
n = 0;
while (!isdigit(c = read_ch()) && c != '-');
long long sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
} in( "fmcm.in" );
fstream out( "fmcm.out", ios::out );
const int DIM = 355;
const int INF = 0x3f3f3f3f;
int dp[DIM], fth[DIM], dst[DIM];
int cap[DIM][DIM], cst[DIM][DIM];
bitset<DIM> mrk; vector<int> edg[DIM]; deque<int> que;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> prq;
bool bf( int s, int d, int n ) {
fill( dst + 1, dst + n + 1, INF );
bool ok = false;
dst[s] = 0; mrk.reset(); mrk[s] = 1;
for( que.push_back( s ); que.empty() == false; que.pop_front() ) {
int x = que.front(); mrk[x] = false;
for( int y : edg[x] ) {
if( cap[x][y] && dst[y] > dst[x] + cst[x][y] ) {
dst[y] = dst[x] + cst[x][y]; fth[y] = x;
if( mrk[y] == false ) {
if( y != d ) {
que.push_back( y );
mrk[y] = true;
}
else
ok = true;
}
}
}
}
return ok;
}
bool dj( int s, int d, int n ) {
fill( dp + 1, dp + n + 1, INF ); bool ok = false;
dp[s] = 0;
for( prq.push( make_pair( 0, s ) ); prq.empty() == false; ) {
pair<int, int> x = prq.top(); prq.pop();
if( dp[x.second] != x.first )
continue;
for( int y : edg[x.second] ) {
int c = dst[x.second] - dst[y] + cst[x.second][y];
if( cap[x.second][y] && dp[y] > dp[x.second] + c ) {
dp[y] = dp[x.second] + c; fth[y] = x.second;
if( y != d )
prq.push( make_pair( dp[y], y ) );
else
ok = true;
}
}
}
return ok;
}
int main( void ) {
ios::sync_with_stdio( false );
int n, m, s, d;
in >> n >> m >> s >> d;
for( int i = 1; i <= m; i ++ ) {
int x, y, c, z;
in >> x >> y >> c >> z;
cap[x][y] = c; cst[x][y] = z;
cap[y][x] = 0; cst[y][x] = -z;
edg[x].push_back( y );
edg[y].push_back( x );
}
bf( s, d, n );
int cmn = 0;
while( dj( s, d, n ) ) {
int mnm = INF;
for( int i = d; i != s; i = fth[i] )
mnm = min( mnm, cap[fth[i]][i] );
if( mnm == 0 )
continue;
for( int i = d; i != s; i = fth[i] ) {
cmn += cst[fth[i]][i] * mnm;
cap[fth[i]][i] -= mnm;
cap[i][fth[i]] += mnm;
}
}
out << cmn << endl;
return 0;
}