題目描述:網絡流裸題
問題描述
一個有向圖,求1到N的最大流
輸入格式
第一行N M,表示點數與邊數
接下來M行每行s t c表示一條從s到t的容量為c的邊
輸出格式
一個數最大流量
樣例輸入
6 10
1 2 4
1 3 8
2 3 4
2 4 4
2 5 1
3 4 2
3 5 2
4 6 7
5 4 6
5 6 3
樣例輸出
思路
看一下大佬講的網絡流吧,看完就懂了:https://blog.csdn.net/A_Comme_Amour/article/details/79356220
代碼
// 算法訓練:網絡流裸題
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1000 + 10;
const int INF = 0x7fffffff;
int n, m, g[maxn][maxn];
int maxflow = 0;
int increase = 0;
int pre[maxn], flow[maxn];
queue<int> q;
int bfs(int s, int t)
{
while (!q.empty())
q.pop();
q.push(1);
for (int i = 1; i <= t; i++)
{
pre[i] = -1;
}
pre[s] = 0;
flow[s] = INF;
int ok = false;
while (!q.empty())
{
int a = q.front();
q.pop();
if (a == t)
break;
for (int i = 1; i <= t; i++)
{
if (g[a][i] > 0 && pre[i] == -1)
{
pre[i] = a;
flow[i] = min(flow[a], g[a][i]);
q.push(i);
if (i == t)
{
ok = true;
break;
}
}
}
if (ok)
break;
}
if (pre[t] == -1)
return -1;
else
return flow[t];
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++)
{
int s, t, c;
scanf("%d%d%d", &s, &t, &c);
g[s][t] += c;
}
while ((increase = bfs(1, n)) != -1)
{
maxflow += increase;
int b = n;
while (b != 1)
{
g[b][pre[b]] += increase;
g[pre[b]][b] -= increase;
b = pre[b];
}
}
printf("%d", maxflow);
return 0;
}