Pagini recente » Cod sursa (job #811976) | Cod sursa (job #1160776) | Cod sursa (job #1242116) | Cod sursa (job #2628004) | Cod sursa (job #301949)
Cod sursa(job #301949)
//Code by Patcas Csaba
//Time complexity: O(n*m^2)
//Space complexity: O(m+n)
//Method: Edmonds-Karp dupa capul meu pe matrice si liste de vecini
//Working time: 30 minutes
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
#define in_file "maxflow.in"
#define out_file "maxflow.out"
#define VI vector <int>
#define FORN(i,n) for (int i=0;i<n;++i)
#define FOR(i,a,b) for (int i=a;i<=b;++i)
#define ALL(x) x.begin(), x.end()
#define PB push_back
#define S size()
#define inf 111111
int n,m,solution;
vector <VI> cap, f, g;
VI father, ind;
void bf()
{
queue <int> l;
l.push(1);
while (!father[n] && !l.empty())
{
int node=l.front();
FORN(i,g[node].S)
{
int aux=g[node][i];
if (!father[aux] && cap[node][aux]>f[node][aux])
{
father[aux]=node;
ind[aux]=i;
l.push(aux);
}
}
FORN(i,g[node].S)
{
int aux=g[node][i];
if (!father[aux] && f[aux][node])
{
father[aux]=-node;
ind[aux]=i;
l.push(aux);
}
}
l.pop();
}
}
int IncreaseFlow()
{
int node=n, flow=inf;
while (node!=1)
{
if (father[node]>0) flow=min(flow,cap[father[node]][node]-f[father[node]][node]);
else flow=min(flow,f[node][-father[node]]);
node=abs(father[node]);
}
node=n;
while (node!=1)
{
if (father[node]>0) f[father[node]][node]+=flow;
else f[node][-father[node]]-=flow;
node=abs(father[node]);
}
return flow;
}
void EdmondsKarp()
{
father.resize(n+1);
ind.resize(n+1);
solution=0;
while (1)
{
fill(ALL(father),0);
bf();
if (father[n])
{
int aux=IncreaseFlow();
solution+=aux;
}
else break;
}
}
void AddEdge(int node1, int node2, int c)
{
g[node1].PB(node2);
g[node2].PB(node1);
cap[node1][node2]=c;
}
int main()
{
FILE* fin=fopen(in_file,"r");
fscanf(fin,"%d%d",&n,&m);
g.resize(n+1);
cap.resize(n+1,VI(n+1,-1));
f.resize(n+1,VI(n+1));
FORN(q,m)
{
int x,y,z;
fscanf(fin,"%d%d%d",&x,&y,&z);
AddEdge(x,y,z);
}
fclose(fin);
EdmondsKarp();
FILE* fout=fopen(out_file,"w");
fprintf(fout,"%d",solution);
fclose(fout);
return 0;
}