Pagini recente » Cod sursa (job #450894) | Cod sursa (job #2500279) | Cod sursa (job #2489507) | Cod sursa (job #2698025) | Cod sursa (job #782261)
Cod sursa(job #782261)
#include <fstream>
#include <vector>
#include <queue>
#define MAXN 355
#define INF 2000000000
using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");
struct nod_q{
int nod,dis;};
struct Comp{
bool operator()(nod_q a,nod_q b){
return a.dis>b.dis;}};
int n,m,s,d,x,y,z,t,fx[MAXN][MAXN],c[MAXN][MAXN],cost[MAXN][MAXN],dist[MAXN],back[MAXN],cst,ctot,mn,cnt;
vector<int> G[MAXN];
queue<int> q;
priority_queue<nod_q,vector<nod_q>,Comp> h;
nod_q aux;
bool uz[MAXN];
void belman_ford();
bool djikstra();
int main(){
int i,j;
f>>n>>m>>s>>d;
for(i=1;i<=m;i++){
f>>x>>y>>z>>t;
G[x].push_back(y);
G[y].push_back(x);
c[x][y]=z;
cost[x][y]=t;
cost[y][x]=-t;}
belman_ford();
cst=dist[d];
while(djikstra()){
x=d;
mn=INF;
while(back[x]){
y=x;
x=back[x];
if(c[x][y]-fx[x][y]<mn)
mn=c[x][y]-fx[x][y];}
x=d;
while(back[x]){
y=x;
x=back[x];
fx[x][y]+=mn;
fx[y][x]-=mn;}
cst+=dist[d];
ctot+=cst*mn;}
g<<ctot<<'\n';
f.close();
g.close();
}
void belman_ford(){
int i;
for(i=1;i<=n;i++)
dist[i]=INF;
dist[s]=0;
q.push(s);
uz[s]=1;
while(!q.empty()){
x=q.front();
uz[x]=0;
q.pop();
y=dist[x];
for(i=0;i<G[x].size();i++)
if(y+cost[x][G[x][i]]<dist[G[x][i]]&&c[x][G[x][i]]){
dist[G[x][i]]=y+cost[x][G[x][i]];
if(!uz[G[x][i]]){
uz[G[x][i]]=1;
q.push(G[x][i]);}}}}
bool djikstra(){
int i,j;
for(i=1;i<=n;i++)
for(j=0;j<G[i].size();j++)
if(dist[i]<INF&&dist[G[i][j]]<INF)
cost[i][G[i][j]]+=dist[i]-dist[G[i][j]];
for(i=1;i<=n;i++){
dist[i]=INF;
uz[i]=0;}
dist[s]=cnt=0;
while(!h.empty())
h.pop();
aux.nod=s;
aux.dis=0;
h.push(aux);
while(cnt<n&&!h.empty()){
aux=h.top();
h.pop();
while(uz[aux.nod]&&!h.empty()){
aux=h.top();
h.pop();}
x=aux.nod;
if(uz[x])
break;
cnt++;
uz[x]=1;
y=dist[x];
for(i=0;i<G[x].size();i++){
if(y+cost[x][G[x][i]]<dist[G[x][i]]&&fx[x][G[x][i]]<c[x][G[x][i]]){
dist[G[x][i]]=y+cost[x][G[x][i]];
back[G[x][i]]=x;
aux.nod=G[x][i];
aux.dis=dist[G[x][i]];
h.push(aux);}}}
return uz[d];}