PAT顶级1003 - 最大网络流

// PAT top 1003
// https://pintia.cn/problem-sets/994805148990160896/problems/994805155688464384

#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

using cap_type = int;

const cap_type INF = 1 << 28;
const int MAX_N = 1024;

struct Edge
{
    int to;
    int next;
    cap_type cap;
    Edge(int to = 0, int next = 0, cap_type cap = 0) : to(to), next(next), cap(cap) {}
} G[2 * MAX_N];
int head[MAX_N], deg;
bool used[MAX_N];
void init(int n);
void add_edge(int u, int v, cap_type cap);
cap_type dfs(int T, int n, cap_type f);
cap_type max_flow(int S, int T);

int main()
{
    string u, v;
    int N, M = 3;

    cin >> u >> v >> N;

    init(N);
    unordered_map<string, int> dir{{u, 1}, {v, 2}};
    for (cap_type cap; N--;)
    {
        cin >> u >> v >> cap;
        int &_u = dir[u], &_v = dir[v];
        if (!_u)
            _u = M++;
        if (!_v)
            _v = M++;
        add_edge(_u, _v, cap);
    }
    cout << max_flow(1, 2);
    return 0;
}

void init(int n)
{
    fill(head, head + n + 8, -1);
    deg = 0;
}

void add_edge(int u, int v, cap_type cap)
{
    G[deg] = Edge(v, head[u], cap);
    head[u] = deg++;
    G[deg] = Edge(u, head[v], 0);
    head[v] = deg++;
}

cap_type dfs(int T, int n, cap_type f)
{
    used[n] = true;
    if (n == T)
    {
        return f;
    }
    for (int i = head[n]; ~i; i = G[i].next)
    {
        auto &e = G[i];
        if (!used[e.to] && e.cap)
        {
            cap_type d = dfs(T, e.to, min(e.cap, f));
            if (d)
            {
                e.cap -= d;
                G[i ^ 1].cap += d;
                return d;
            }
        }
    }
    return 0;
}

cap_type max_flow(int S, int T)
{
    cap_type flow = 0, f;
    do
    {
        fill(used, used + MAX_N, false);
        f = dfs(T, S, INF);
        flow += f;
    } while (f);
    return flow;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值