Pagini recente » Cod sursa (job #1272030) | Cod sursa (job #2621289) | Cod sursa (job #2621290) | Cod sursa (job #3186031) | Cod sursa (job #2960330)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
const int maxx = 351, mmaxx = (int)(1e9);
int cty[maxx][maxx], tata[maxx], cost[maxx][maxx];
vector <int> dist(maxx), pseudoDist(maxx);
vector <vector<int>> adjL;
bitset <maxx> viz(false);
int n, m, i, nr1, nr2, nr3, flow, minn, j, start, endd, nr4;
queue <int> q;
void bellford(){
while (!q.empty())
q.pop();
q.push(start);
viz.reset();
dist.assign(n+1, mmaxx);
dist[start] = 0;
while(!q.empty()){
nr1 = q.front();
q.pop();
viz[nr1]=false;
for(auto &i : adjL[nr1]){
if (cty[nr1][i] > 0 && dist[i] > dist[nr1] + cost[nr1][i]){
dist[i] = dist[nr1] + cost[nr1][i];
tata[i] = nr1;
if (viz[i] == false){
viz[i] = true;
q.push(i);
}
}
}
}
}
int dijkstra(){
priority_queue <pair <int, int>, vector <pair<int, int>>, greater <pair<int, int>>> hip;
hip.push({0, start});
pseudoDist.assign(n+1, mmaxx);
pseudoDist[start] = 0;
memset(tata, 0, sizeof(tata));
pair <int, int> aici;
while (!hip.empty()){
aici = hip.top();
hip.pop();
if(aici.first != mmaxx){
for (auto & vecin : adjL[aici.second]){
if (cty[aici.second][vecin] > 0 && pseudoDist[vecin] > pseudoDist[aici.second] + cost[aici.second][vecin] + dist[aici.second] - dist[vecin]){
pseudoDist[vecin] = pseudoDist[aici.second] + cost[aici.second][vecin] + dist[aici.second] - dist[vecin];
hip.push({pseudoDist[vecin], vecin});
tata[vecin] = aici.second;
}
}
}
}
if (pseudoDist[endd] == mmaxx)
return mmaxx;
nr1 = dist[start]; nr2 = dist[endd];
for (i = 1; i <= n; ++i){
dist[i] = pseudoDist[i] - nr1 + dist[i];
}
return pseudoDist[endd] - nr1 + nr2;
}
int main(){
fin >>n >> m >> start >> endd;
adjL.assign(n+1, vector<int>());
for(i = 0; i < m; ++i){
fin >> nr1 >> nr2 >> nr3 >> nr4;
adjL[nr1].push_back(nr2);
adjL[nr2].push_back(nr1);
cty[nr1][nr2] = nr3;
cost[nr1][nr2] = nr4;
cost[nr2][nr1] = -nr4;
}
flow = 0;
bellford();
while(true){ /// nr1 -> dist totala pana in destinatie
nr1 = dijkstra();
if (nr1 == mmaxx)
break;
minn = maxx;
for (i = endd; i != start; i = tata[i]){
minn = min(minn, cty[tata[i]][i]);
}
for (i = endd; i != start; i = tata[i]){
cty[tata[i]][i] -= minn;
cty[i][tata[i]] += minn;
}
flow += minn * nr1;
}
fout << flow << '\n';
return 0;
}