Pagini recente » Monitorul de evaluare | Cod sursa (job #1497481) | Cod sursa (job #394953) | Diferente pentru template/despre-infoarena intre reviziile 19 si 20 | Cod sursa (job #1154848)
#include<fstream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include<queue>
#define abs(x) ((x>0)?(x):(-(x)))
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define ll long long
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
void Read(int& x){in>>x;}
const int Nmax = 351;
const int Mmax = 12501;
const int INF = 0x3f3f3f3f;
int N,M,sour,dest;
vector<int> G[Nmax],Cost[Nmax];
int C[Nmax][Nmax];
int D[Nmax],fD[Nmax],anoD[Nmax],pred[Nmax];
void cpy(int A[],int B[]){
for(int i=1;i<=N;i++) A[i]=B[i];
}
queue<int> q; int inQ[Nmax];
int bellmanford(){
memset(D,INF,sizeof(D)); D[sour]=0;
q.push(sour),inQ[sour]=1;
while(!q.empty()){
int x=q.front(); q.pop();
inQ[x]=0;
for(int i=0;i<G[x].size();i++){
int to=G[x][i],cost=Cost[x][i];
if(D[x]+cost<D[to] && C[x][to]!=0){
D[to]=D[x]+cost;
if(!inQ[to]) q.push(to),inQ[to]=1;
}
}
}
cpy(fD,D);
return D[dest]!=INF;
}
struct state{int nod,cost;state(int _t,int _c){nod=_t,cost=_c;}};
struct cmp{inline bool operator()(const state& a,const state& b)const{return a.cost>b.cost;}};
priority_queue<state,vector<state>,cmp> h;
int dijk(){
memset(D,INF,sizeof(D));
memset(anoD,INF,sizeof(anoD));
D[sour]=anoD[sour]=0;
h.push(state(sour,0));
while(!h.empty()){
state p=h.top(); h.pop();
if(D[p.nod] != p.cost) continue; //???
for(int i=0;i<G[p.nod].size();i++){
int to=G[p.nod][i],cost=Cost[p.nod][i]+fD[p.nod]-fD[to];
if(p.cost+cost<D[to] && C[p.nod][to]!=0){
D[to]=p.cost+cost;
anoD[to]=anoD[p.nod]+Cost[p.nod][i];
pred[to]=p.nod;
h.push(state(to,D[to]));
}
}
}
cpy(fD,anoD);
return D[dest]!=INF;
}
int MF,MFMC;
int addpath(){
int y=dest,Min=INF;
while(y!=sour){
Min=min(Min,abs(C[pred[y]][y]));
y=pred[y];
}
y=dest;
while(y!=sour){
C[pred[y]][y]-=Min;
C[y][pred[y]]+=Min;
y=pred[y];
}
MF+=Min;
return Min*fD[dest];
}
int main(){
Read(N),Read(M),Read(sour),Read(dest);
int x,y,c,z;
for(int i=1;i<=M;i++){
Read(x),Read(y),Read(c),Read(z);
G[x].push_back(y);
Cost[x].push_back(z);
C[x][y]=c;
G[y].push_back(x);
Cost[y].push_back(-z);
C[y][x]=0;
}
bellmanford();
int r;
while(dijk()){
r=addpath();
MFMC+=r;
}
out<<MFMC<<'\n';
return 0;
}