EK算法76ptsWA求调
查看原帖
EK算法76ptsWA求调
996278
yangshangqi楼主2024/1/25 20:09

代码如下:

#include <bits/stdc++.h>
#define ll long long 
using namespace std;
const ll N = 10007, M = 100007, INF = 100000007;
struct node{
	ll to, val, nxt;
}e[M << 1];
ll n, m, S, T, tot;
ll head[N], dis[N], pre[N];
bool vis[N];
queue<ll> q;
inline int read() {
    int q = 0;
    char qw;
    do {
        qw = getchar();
    } while (!('0' <= qw && qw <= '9'));
    while ('0' <= qw && qw <= '9') q = q * 10 + qw - '0', qw = getchar();
    return q;
}
inline void write(int x) {
    int sta[35];
    int top = 0;
    do {
        sta[top++] = x % 10, x /= 10;
    } while (x);
    while (top) putchar(sta[--top] + '0');
}
void add(ll a, ll b, ll c){
	e[tot].to = b; e[tot].val = c, e[tot].nxt = head[a], head[a] = tot++ ;
	e[tot].to = a; e[tot].val = 0, e[tot].nxt = head[b], head[b] = tot++ ;
}
bool bfs(){
	while(!q.empty()) q.pop();
    memset(vis, false, sizeof vis);
    q.push(S), vis[S] = true, dis[S] = INF;
    while (!q.empty()){
        ll t = q.front();
        q.pop();
        for (ll i = head[t]; i != -1; i = e[i].nxt){
            ll v = e[i].to;
            if (!vis[v] && e[i].val){
                vis[v] = true;
                dis[v] = min(dis[t], e[i].val);
                pre[v] = i;
                if (v == T) return true;
                q.push(v);
            }
        }
    }
    return false;
}
ll EK(){
    ll r = 0;
    while (bfs()){
        r += dis[T];
        for (ll i = T; i != S; i = e[pre[i] ^ 1].to) 
            e[pre[i]].val -= dis[T], e[pre[i] ^ 1].val += dis[T];
    }
    return r;
}
int main(){
    n=read();
    m=read();
    S=read();
    T=read();
    memset(head, -1, sizeof head);
    while (m -- ){
        ll a, b, c;
        a=read();
        b=read();
        c=read();;
        add(a, b, c);
    }
    write(EK());
    return 0;
}
2024/1/25 20:09
加载中...