Pagini recente » Cod sursa (job #2682254) | Cod sursa (job #2710836) | Cod sursa (job #423733) | Cod sursa (job #778302) | Cod sursa (job #3033387)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f ("fmcm.in");
ofstream g ("fmcm.out");
struct elem{
int nod,cost;
bool operator < (const elem &aux)
const{
return aux.cost<cost;
}
};
int dist[351],distdj1[351],distdj2[351],capacitate[351][351],costuri[351][351];
bool viz[351];
vector<pair<int,int>>muchii;
priority_queue < elem>q;
vector<int>adiacenta[351];
int n,m,s,d,rasp_cost;
int tati[351];
void bellman()
{
for(int i = 1;i<=n;i++)
dist[i]=(1<<30)-1;
dist[s] = 0;
q.push({s,0});
while(!q.empty())
{
int curent = q.top().nod;
int cost_curent = q.top().cost;
q.pop();
for(auto x:adiacenta[curent])
{
int nod_nou = x;
int cost_nou = costuri[curent][nod_nou];
if(dist[nod_nou]>cost_curent+cost_nou && capacitate[curent][nod_nou])
{
dist[nod_nou]= cost_curent+cost_nou;
q.push({nod_nou,dist[nod_nou]});
}
}
}
}
bool dj()
{
for(int i = 1;i<=n;i++)
{
distdj1[i] = distdj2[i] = (1<<30)-1;
tati[i] = i;
viz[i] = 0;
}
q.push({s,0});
distdj1[s] = distdj2[s] = 0;
while(!q.empty())
{
int curent = q.top().nod;
int cost = q.top().cost;
q.pop();
if(distdj1[curent]!=cost)
continue;
for(auto x:adiacenta[curent])
{
if(capacitate[curent][x]!=0)
{
int nouadist = distdj1[curent]+costuri[curent][x]+dist[curent]-dist[x];
if(nouadist <distdj1[x])
{
distdj1[x] = nouadist;
q.push({x,distdj1[x]});
distdj2[x] = distdj2[curent]+costuri[curent][x];
tati[x] = curent;
}
}
}
}
if(distdj1[d]!=(1<<30)-1)
return 1;
return 0;
}
int main()
{
std::ios::sync_with_stdio(false);
f >> n >> m>>s>>d;
for(int i=1;i<=m;i++)
{
int x,y,c,cost;
f >> x >> y >> c>>cost;
muchii.push_back({x,y});
adiacenta[x].push_back(y);
adiacenta[y].push_back(x);
capacitate[x][y]=c;
costuri[x][y] = cost;
costuri[y][x] = -cost;
}
bellman();
while(dj())
{
int flux = (1<<30)-1;
int nod_start = d;
while(nod_start!=s)
{
flux = min(flux,capacitate[tati[nod_start]][nod_start]);
nod_start = tati[nod_start];
}
nod_start = d;
if(flux==0)
continue;
while(nod_start!=s)
{
capacitate[tati[nod_start]][nod_start] -=flux;
capacitate[nod_start][tati[nod_start]] +=flux;
nod_start=tati[nod_start];
}
rasp_cost+=flux*distdj2[d];
}
g << rasp_cost;
}