Pagini recente » Rating Maria Fee (Nutzi) | Cod sursa (job #1421479) | Profil katakuna | Cod sursa (job #149872) | Cod sursa (job #901931)
Cod sursa(job #901931)
#include<fstream>
#define nmax 501
#define inf 1<<30
using namespace std;
struct nod_lista{
int val;
nod_lista *link;
};
nod_lista *G[nmax],*Last[nmax];
int dist[nmax],Q[4*nmax],cap[nmax][nmax],F[nmax][nmax],cost[nmax][nmax],T[nmax];
int N,M,S,D,Flux,CostFlux;
void adauga(int unde,int ce)
{
nod_lista *q=new nod_lista;
q->val=ce;
q->link=NULL;
if(!G[unde])
G[unde]=Last[unde]=q;
else
{
Last[unde]->link=q;
Last[unde]=q;
}
}
void citeste()
{
ifstream f("fmcm.in");
int i,x,y,cc,c;
f>>N>>M>>S>>D;
for(i=1;i<=M;i++)
{
f>>x>>y>>cc>>c;
adauga(x,y);
adauga(y,x);
cap[x][y]=cc;
cost[x][y]=c;
cost[y][x]=-c;
}
f.close();
}
int BellmanFord()
{
int p,q,nod,vecin,i;
nod_lista *it;
for(i=1;i<=N;i++)
dist[i]=inf;
dist[S]=0;
p=q=0;
Q[++q]=S;
while(p<q)
{
nod=Q[++p];
it=G[nod];
while(it)
{
vecin=it->val;
if(cap[nod][vecin]-F[nod][vecin]>0 && dist[vecin]>dist[nod]+cost[nod][vecin])
{
dist[vecin]=dist[nod]+cost[nod][vecin];
Q[++q]=vecin;
T[vecin]=nod;
}
it=it->link;
}
}
if(dist[D]!=inf)
return 1;
return 0;
}
void saturare()
{
int cmin=inf,nod;
nod=D;
while(nod!=S)
{
if(cap[T[nod]][nod]-F[T[nod]][nod]<cmin)
cmin=cap[T[nod]][nod]-F[T[nod]][nod];
nod=T[nod];
}
nod=D;
while(nod!=S)
{
F[T[nod]][nod]+=cmin;
F[nod][T[nod]]-=cmin;
nod=T[nod];
}
Flux+=cmin;
CostFlux+=cmin*dist[D];
}
void rezolva()
{
while(BellmanFord())
saturare();
}
void scrie()
{
ofstream g("fmcm.out");
g<<CostFlux<<'\n';
g.close();
}
int main()
{
citeste();
rezolva();
scrie();
return 0;
}