Pagini recente » Cod sursa (job #423609) | Cod sursa (job #1910195) | Cod sursa (job #2087716) | Cod sursa (job #2209286) | Cod sursa (job #2905059)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
int n,m,s,d;
int x,y,c,z;
struct Edge
{
int x,y,c,z;
};
class Graph
{
private:
vector <vector <int>> adj;
int cntEdges;
int cntVertices;
public:
Graph(int n)
{
adj.resize(n+1);
cntVertices=n;
}
vector <Edge> edges;
void AddEdge(int u,int v,int c,int z)
{
edges.push_back({u,v,c,z});
adj[u].push_back(cntEdges);
adj[v].push_back(cntEdges);
cntEdges++;
}
/// modifica edges[i].z (sa fie toate pozitive si sp-urile sa ramana) folosind adj
void BellmanFord()
{
}
bool Dijkstra(int source,int sink,vector <int> flow,vector <int> cap,vector <int> &path)
{
priority_queue <pair <int,int>,vector <pair <int,int>>,greater <int,int>> pq;
vector <int> dist(cntVertices+1,1e9);
vector <pair <int,int>> par(cntVertices+1);
pq.push(0,source);
while(!pq.empty())
{
pair <int,int> aux=pq.top();
pq.pop();
for(auto incEdge:adj[aux.second])
{
if(flow[incEdge]==cap[incEdge])
continue;
int otherEnd=egdes[incEdge].x+egdes[incEdge].y-aux.second;
if(dist[otherEnd]>dist[aux.second]+edges[incEdge].z)
{
dist[otherEnd]=dist[aux.second]+edges[incEdge].z;
par[otherEnd]=make_pair(aux.second,incEdge);
pq.push(make_pair(otherEnd,dist[otherEnd]));
}
}
}
if(dist[sink]==1e9)
return false;
stack <int> st;
int node=sink;
while(node!=source)
{
st.push(par[node].second);
node=par[node].first;
}
path.clear();
while(!st.empty())
{
path.push_back(st.top());
st.pop();
}
return true;
}
};
class MaxFlow
{
private:
vector <int> flow,cap;
Graph h;
public:
MaxFlow(Graph g)
{
h=g;
flow.resize(h.cntVertices+1);
cap.resize(h.cntVertices+1);
}
int solve()
{
for(int i=0; i<h.cntEdges; i++)
cap[i]=h.edges[i].c;
vector <int> path;
int ans=0;
while(!h.Dijkstra(s,d,flow,cap,path))
{
int minim=2e9;
for(auto edge:path)
minim=min(minim,cap[edge]-flow[edge]);
for(auto edge:path)
flow[edge]+=minim;
ans+=minim;
}
return ans;
}
};
int main()
{
fin>>n>>m>>s>>d;
Graph G(n);
for(int i=1; i<=m; i++)
{
fin>>x>>y>>c>>z;
G.AddEdge(x,y,c,z);
}
MaxFlow F(G);
fout<<F.solve()<<"\n";
return 0;
}