当前位置: 代码迷 >> 综合 >> HOJ 3549 Flow Problem(最大流,裸题)
  详细解决方案

HOJ 3549 Flow Problem(最大流,裸题)

热度:59   发布时间:2023-12-13 19:12:18.0

最大流,裸题
题目意思:
给你一个N个顶点M条边的有向图,要你求1号点到N号点的最大流.
本题要点:
1、套用 RK 算法模板

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int MaxN = 210, MaxM = 2010;
const int inf = 1 << 29;
int head[MaxN], ver[MaxM], edge[MaxM], Next[MaxM], vis[MaxN];
int incf[MaxN], pre[MaxN];
int g[MaxN][MaxN];	//邻接矩阵,用于去重边
int T, n, m, st, ed, tot, maxflow;void add(int x, int y, int z)
{
    ver[++tot] = y, edge[tot] = z, Next[tot] = head[x], head[x] = tot;ver[++tot] = x, edge[tot] = 0, Next[tot] = head[y], head[y] = tot;
}bool bfs()
{
    memset(vis, 0, sizeof vis);queue<int> q;q.push(st);vis[st] = 1;incf[st] = inf;		//增光路上各边的最小剩余容量while(q.size()){
    int x = q.front(); q.pop();for(int i =head[x]; i; i = Next[i]){
    if(edge[i]){
    int y = ver[i];if(vis[y])	continue;incf[y] = min(incf[x], edge[i]);pre[y] = i;	//记录前驱q.push(y), vis[y] = 1;if(y == ed)	return 1;}}}return 0;
}void update()
{
    int x = ed;while(x != st){
    int i = pre[x];edge[i] -= incf[ed];;edge[i ^ 1] += incf[ed];x = ver[i ^ 1];}maxflow += incf[ed];
}int main()
{
    int x, y, z;scanf("%d", &T);for(int t = 1; t <= T; ++t){
    scanf("%d%d", &n, &m);memset(head, 0, sizeof head);memset(Next, 0, sizeof Next);memset(g, 0, sizeof g);st = 1, ed = n, tot = 1, maxflow = 0;for(int i = 0; i < m; ++i){
    scanf("%d%d%d", &x, &y, &z);g[x][y] += z;}for(int i = 1; i <= n; ++i){
    for(int j = 1; j <= n; ++j){
    if(g[i][j]){
    add(i, j, g[i][j]);}}}while(bfs()){
    update();}printf("Case %d: %d\n", t, maxflow);}return 0;
}/* 2 3 2 1 2 1 2 3 1 3 3 1 2 1 2 3 1 1 3 1 *//* Case 1: 1 Case 2: 2 */
  相关解决方案