Pagini recente » Cod sursa (job #2146576) | Cod sursa (job #2080686) | Cod sursa (job #1577970) | Cod sursa (job #2965638) | Cod sursa (job #302030)
Cod sursa(job #302030)
//Code by Patcas Csaba
//Time complexity: O(n*m^2)
//Space complexity: O(m+n)
//Method: Edmonds-Karp dupa capul meu numai pe 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
struct Tedge
{
int node,cap,f,inv;
};
int n,m,solution;
vector <vector <Tedge> > g, g2;
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)
{
Tedge aux=g[node][i];
if (!father[aux.node] && aux.cap>aux.f)
{
father[aux.node]=node;
ind[aux.node]=i;
l.push(aux.node);
}
}
FORN(i,g2[node].S)
{
Tedge aux=g2[node][i];
if (!father[aux.node] && aux.f)
{
father[aux.node]=-node;
ind[aux.node]=i;
l.push(aux.node);
}
}
l.pop();
}
}
int IncreaseFlow(int to)
{
int node=to, flow=inf;
while (node!=1)
{
if (father[node]>0)
{
Tedge aux=g[father[node]][ind[node]];
flow=min(flow,aux.cap-aux.f);
}
else
{
Tedge aux=g2[-father[node]][ind[node]];
flow=min(flow,aux.f);
}
node=abs(father[node]);
}
node=to;
while (node!=1)
{
if (father[node]>0)
{
g[father[node]][ind[node]].f+=flow;
g2[node][g[father[node]][ind[node]].inv].f+=flow;
}
else
{
g2[-father[node]][ind[node]].f-=flow;
g[node][g2[-father[node]][ind[node]].inv].f-=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])
{
FORN(i,g2[n].S)
if (father[g2[n][i].node])
{
int aux=IncreaseFlow(g2[n][i].node);
solution+=aux;
}
}
else break;
}
}
void AddEdge(int node1, int node2, int c)
{
Tedge aux;
aux.node=node2;
aux.cap=c;
aux.f=0;
g[node1].PB(aux);
aux.node=node1;
aux.cap=c;
aux.f=0;
aux.inv=g[node1].S-1;
g2[node2].PB(aux);
g[node1][g[node1].S-1].inv=g2[node2].S-1;
}
int main()
{
FILE* fin=fopen(in_file,"r");
fscanf(fin,"%d%d",&n,&m);
g.resize(n+1);
g2.resize(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;
}