Pagini recente » Cod sursa (job #2314065) | Cod sursa (job #1340913) | Cod sursa (job #2789703) | Cod sursa (job #2675120) | Cod sursa (job #3033282)
#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];
int 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;
tati[nod_nou]=curent;
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(viz[curent])
continue;
viz[curent] = 1;
if(curent==d)
continue;
for(auto x:adiacenta[curent])
{
if(capacitate[curent][x]!=0 && distdj1[x]>cost+costuri[curent][x] && !viz[x])
{
distdj1[x] = cost+costuri[curent][x];
q.push({x,distdj1[x]});
distdj2[x] = distdj2[curent] - dist[curent]+dist[x]+costuri[curent][x];
tati[x] = curent;
}
}
}
if(distdj1[d]!=(1<<30)-1)
return 1;
return 0;
}
int main()
{
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();
for(auto x:muchii)
{
int x1 = x.first;
int x2 = x.second;
costuri[x1][x2]+=dist[x1]-dist[x2];
costuri[x2][x1]+=dist[x2]-dist[x1];
}
while(dj())
{
for(auto x:adiacenta[d])
{
if(capacitate[x][d]!=0 && dist[x]!=(1<<30)-1)
{
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;
}