Pagini recente » Cod sursa (job #1143495) | Cod sursa (job #1705684) | Cod sursa (job #341110) | Cod sursa (job #2351310) | Cod sursa (job #906094)
Cod sursa(job #906094)
#include <fstream>
#include <set>
#include <utility>
#include <queue>
#include <vector>
#define mp make_pair
#define N 360
#define M 13000
#define oo int(2e9)
using namespace std;
queue<int> Q;
bool inq[N];
vector<int> :: iterator it;
vector<int> G[N];
int real[N], prev[N], D[N], Mx[M], My[M], Mz[M], C[N][N], cost[N][N], Cost[N][N];
int flow, sol, i, n, m, x, y, z, c, Src, Dest;
set<pair<int, int> >S;
void Bellman()
{
for(i = 1; i <= n; i++) D[i] = oo;
D[Src] = 0;
Q.push(Src);
while(!Q.empty())
{
x = Q.front();
Q.pop();
inq[x] = 0;
for(it = G[x].begin(); it != G[x].end(); ++it)
if(C[x][*it] and D[*it] > D[x] + cost[x][*it])
{
D[*it] = D[x] + cost[x][*it];
if(!inq[*it])
{
inq[*it] = 1;
Q.push(*it);
}
}
}
for(i = 1; i <= m; i++)
{
x = Mx[i]; y = My[i]; z = Mz[i];
Cost[x][y] = D[x] + z - D[y];
Cost[y][x] = D[y] - z - D[x];
}
}
bool Dijkstra()
{
for(i = 1; i <= n; i++) D[i] = oo;
while(!S.empty()) S.erase(S.begin());
D[Src] = 0;
real[Src] = 0;
S.insert(mp(0, Src));
while(!S.empty())
{
x = S.begin()->second;
S.erase(S.begin());
for(it = G[x].begin(); it != G[x].end(); ++it)
if(C[x][*it] and D[*it] > D[x] + Cost[x][*it])
{
D[*it] = D[x] + Cost[x][*it];
real[*it] = real[x] + cost[x][*it];
prev[*it] = x;
S.insert(mp(D[*it], *it));
}
}
return D[Dest] != oo;
}
int main()
{
ifstream fi("fmcm.in");
ofstream fo("fmcm.out");
fi >> n >> m >> Src >> Dest;
for(i = 1; i <= m; i++)
{
fi >> x >> y >> c >> z;
C[x][y] = c;
C[y][x] = 0;
cost[x][y] = z;
cost[y][x] = -z;
Mx[i] = x; My[i] = y; Mz[i] = z;
G[x].push_back(y);
G[y].push_back(x);
}
Bellman();
while(Dijkstra())
{
flow = int(2e9);
for(i = Dest; i != Src; i = prev[i])
flow = min(flow, C[prev[i]][i]);
for(i = Dest; i != Src; i = prev[i])
C[prev[i]][i] -= flow, C[i][prev[i]] += flow;
sol += flow*real[Dest];
}
fo << sol << "\n";
return 0;
}