#include <iostream>
#include <string.h>
#include <deque>
using namespace std;
#define MAX_INT 0x7fffffff
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int N, M, map[210][210], pre[210], node_min[210], path_min[210];
deque<int> Q;
/*为bfs初始化*/
void initialize(int s)
{
int i;
memset(pre, 0, sizeof(pre));
for (i=0 ; i<=M ; i++)
node_min[i] = path_min[i] = MAX_INT;
node_min[s] = 0;
}
bool bfs(int s, int t)
{
int i, crt;
initialize(s);
Q.push_back(s);
while (!Q.empty())
{
crt = Q.front();
Q.pop_front();
for (i=1 ; i<=M ; i++)
{
if (0 != map[crt][i] && (node_min[crt] + map[crt][i] < node_min[i]))
{
node_min[i] = node_min[crt] + map[crt][i];
/*记录最短路径*/
pre[i] = crt;
path_min[i] = MIN(path_min[crt], map[crt][i]);
Q.push_back(i);
}
}
}
if (MAX_INT == node_min[M])
return false;
return true;
}
int max_flow(int s, int t)
{
int crt, fath, min, ret = 0;
while (bfs(s, t))
{
/*按最短路径调整残留网络*/
min = path_min[M];
crt = M;
while (crt != s)
{
fath = pre[crt];
map[fath][crt] -= min;
/*这里为什么要反向增加流??*/
map[crt][fath] += min;
crt = fath;
}
ret += min;
}
return ret;
}
int main(int argc, char *argv[])
{
int i, si, ei, ci, max;
while (cin >> N >> M)
{
memset(map, 0, sizeof(map));
for (i=0 ; i<N ; i++)
{
cin >> si >> ei >> ci;
map[si][ei] += ci;
}
max = max_flow(1, M);
cout << max << endl;
}
}
|