Pagini recente » Cod sursa (job #741932) | Cod sursa (job #2454376) | Cod sursa (job #1376433) | Cod sursa (job #3174356) | Cod sursa (job #2749909)
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstring>
using namespace std;
ifstream cin("fmcm.in");
ofstream cout("fmcm.out");
constexpr int INF = 1e9;
int n, m, source, sink;
vector<pair<int,int>> L[355];
int cap[355][355], flux[355][355], cost[355][355];
int tata[355];
bool bf()
{
memset(tata, 0, sizeof(tata));
vector<int> d(n+1, INF);
d[source] = 0;
queue<int> Q;
Q.push(source);
while (!Q.empty())
{
auto aux = Q.front(); Q.pop();
for (auto i : L[aux])
if (flux[aux][i.first] < cap[aux][i.first] && d[i.first] > i.second + d[aux])
{
d[i.first] = i.second + d[aux];
tata[i.first] = aux;
Q.push(i.first);
}
}
return d[sink] != INF;
}
int main()
{
cin >> n >> m >> source >> sink;
for (int i=1;i<=m;i++)
{
int x, y, z, c;
cin >> x >> y >> z >> c;
cap[x][y] += z;
cost[x][y] += c;
cost[y][x] -= c;
L[x].emplace_back(y,c);
L[y].emplace_back(x,-c);
}
int ans = 0;
while (bf())
{
int nod = sink;
int minim = INF;
while (nod != source)
{
minim = min(minim, cap[tata[nod]][nod] - flux[tata[nod]][nod]);
nod = tata[nod];
}
nod = sink;
while (nod != source)
{
flux[tata[nod]][nod] += minim;
ans += minim * cost[tata[nod]][nod];
nod = tata[nod];
}
}
cout << ans << '\n';
return 0;
}