您的位置:首页 > 其它

MaxFlow(最大流增广路算法)

2011-05-30 19:58 316 查看
#include<iostream>
#include<queue>
#include<fstream>
using namespace std;
const int MAXN = 201;
int cap[MAXN][MAXN];        //残留网络,初始为原图
int flow[MAXN][MAXN];
int vernum;            //节点总数量
int pre[MAXN];
int BFS(const int &s, const int &t)
{
queue<int>q;
memset(pre,-1,sizeof(pre));
q.push(s);
pre[s] = s;
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v=0;v<vernum;v++)
{
if( (pre[v]==-1)&&(flow[u][v]<cap[u][v] || flow[v][u]>0) )
{
pre[v] = u;
q.push(v);
if (v == t) return 1;
}
}
}
return 0;
}
void TrackBack(const int &s, const int &t)
{
int v,min = 0x7fffffff;
int i=t;
while (i != s)
{
v = pre[i];
if (flow[v][i] < cap[v][i])
{
if(min > cap[v][i] - flow[v][i])
min = cap[v][i] - flow[v][i];
}
else
{
if (flow[i][v] > 0)
{
if(min > flow[i][v])
min = flow[i][v];
}
}
i = v;
}

i = t;
while (i != s)
{
v = pre[i];
if (flow[v][i] < cap[v][i])//前进流+min
flow[v][i] += min;
else
{
if (flow[i][v] > 0)
flow[i][v] -= min;
}
i = v;
}
}
int MaxFlow(const int &s, const int &t)
{
while (BFS(s, t))
TrackBack(s, t);
int res = 0;
for(int i=0;i<vernum;i++)
{
if (i != s)
res += flow[s][i];
}
return res;
}
int main()
{
ifstream cin("in.txt");
ofstream cout("out.txt");
int arcnum,f,t,w;
while(cin >> vernum >> arcnum)
{
memset(cap,0,sizeof(cap));
memset(flow,0,sizeof(flow));
while (arcnum--)
{
cin >> f >> t >> w;
cap[f-1][t-1] += w;
}
int ans = MaxFlow(0,vernum-1);
cout << ans << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: