I am trying to solve this Problem on UVA.The question is about finding the max-flow in the graph.I used Edmond-karp algorithm but I am continuously getting wrong answer.Can any one tell me what's wrong in my code ? My code :
#include<bits/stdc++.h>
using namespace std;
#define MX 1000000007
#define LL long long
#define ri(x) scanf("%d",&x)
#define rl(x) scanf("%lld",&x)
#define len(x) x.length()
#define FOR(i,a,n) for(int i=a;i<n;i++)
#define FORE(i,a,n) for(int i=a;i<=n;i++)
template<class T1> inline T1 maxi(T1 a,T1 b){return a>b?a:b;}
template<class T2> inline T2 mini(T2 a,T2 b){return a<b?a:b;}
int parent[101],G[101][101],rG[101][101];
bool bfs(int s,int t,int n)
{
bool vis[n+2];
memset(parent,0,sizeof parent);
memset(vis,0,sizeof vis);
queue<int>Q;
Q.push(s);
vis[s]=true;
while(!Q.empty())
{
int fnt=Q.front();
Q.pop();
for(int v=1;v<=n;v++)
{
if(!vis[v] and G[fnt][v]>0)
{
vis[v]=true;
parent[v]=fnt;
Q.push(v);
}
}
}
return vis[t];
}
int main()
{
int n,tst=1;
ri(n);
while(n)
{
int s,t,c,flow=0;
ri(s),ri(t),ri(c);
FORE(i,1,c)
{
int x,y,z;
ri(x),ri(y),ri(z);
G[x][y]+=z;
G[y][x]+=z;
}
while(bfs(s,t,n))
{
int path=9999999;
for(int v=t;v!=s;v=parent[v])
{
int u=parent[v];
path=mini(path,G[u][v]);
}
for(int v=t;v!=s;v=parent[v])
{
int u=parent[v];
G[u][v]-=path;
G[v][u]+=path;
}
flow+=path;
}
printf("Network %d\nThe bandwidth is %d.\n\n", tst++, flow);
ri(n);
}
}
答案 0 :(得分:0)
You push flow the other way around:
G[u][v]-=path;
G[v][u]+=path;
This should be:
G[u][v] += path;
G[v][u] -= path;
Also, I'm not sure about this part:
if(!vis[v] and G[fnt][v]>0)
[...]
path=mini(path,G[u][v]);
Because you are also allowed to take paths on which the flow is negative. You should not change G
, which seems to be your capacities graph. Instead, you should have a matrix F
that stores how much flow you send. Then your two conditions should be changed to:
if (!vis[v] && G[fnt][v] != F[fnt][v])
[...]
path = mini(path, G[u][v] - F[u][v])
And push flow on F
, not G
.
You seem to have thought about this since you declared a matrix rG
, but you're never using it.
There might be other issues too. It's hard to tell without knowing what problems you're seeing.