Pagini recente » Cod sursa (job #3190765) | Profil EugenStoica | Produse | Cod sursa (job #2802318) | Cod sursa (job #1885759)
#include <bits/stdc++.h>
#define NMAX 360
#define INF 1e9
#define f first
#define s second
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
vector < pair < int , int > > G[NMAX];
int F[NMAX][NMAX],C[NMAX],D[NMAX],ant[NMAX],RD[NMAX];
bool B[NMAX];
struct cmp{
bool operator()(const int &a,const int &b){
return C[a] > C[b];
}
};
priority_queue < int , vector < int >, cmp > PQ;
void bellmanford(const int &n,const int &S){
for(int i = 1; i <= n; i++)
D[i] = INF;
D[S] = 0;
int nod;
B[S] = 1;
deque < int > Q;
Q.push_back(S);
while(!Q.empty()){
nod = Q.front();
Q.pop_front();
B[nod] = 0;
for(auto const &it : G[nod]){
if(!F[nod][it.f] || D[it.f] <= D[nod] + it.s) continue;
D[it.f] = D[nod] + it.s;
if(!B[it.f]){
Q.push_back(it.f);
B[it.f] = 1;
}
}
}
}
bool Dijkstra(const int &S,const int &De,const int &n){
while(!PQ.empty())
PQ.pop();
int nod;
for(int i = 1; i <= n; i++){
C[i] = INF;
RD[i] = 0;
}
C[S] = 0;
PQ.push(S);
while(!PQ.empty()){
nod = PQ.top();
PQ.pop();
for(auto const &it : G[nod]){
if(C[it.f] <= it.s + C[nod] + D[nod] - D[it.f] || F[nod][it.f] == 0) continue;
RD[it.f] = it.s + RD[nod];
C[it.f] = it.s + C[nod] + D[nod] - D[it.f];
PQ.push(it.f);
ant[it.f] = nod;
if(it.f == De)
return 1;
}
}
return 0;
}
int main()
{
ios :: sync_with_stdio(false);
int n,m,x,y,c,f,S,De;
fin >> n >> m >> S >> De;
for(int i = 1; i <= m; i++){
fin >> x >> y >> c >> f;
G[x].push_back({y,f});
G[y].push_back({x,-f});
F[x][y] = c;
}
bellmanford(n,S);
int sol = 0,flow;
while(Dijkstra(S,De,n)){
for(auto const &it : G[De]){
if(C[it.f] == INF || !F[it.f][De]) continue;
ant[De] = it.f;
flow = INF;
for(int i = De; i != S; i = ant[i])
flow = min(flow,F[ant[i]][i]);
if(flow == 0) continue;
for(int i = De; i != S; i = ant[i]){
fout << ant[i] << " " << i << "\n";
F[ant[i]][i] -= flow;
F[i][ant[i]] += flow;
}
sol += flow * RD[De];
fout << flow <<" "<< RD[De] << "\n";
}
}
fout << sol;
return 0;
}