dfs寻找增广路TLE
查看原帖
dfs寻找增广路TLE
582123
Njaso楼主2023/12/15 14:20
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
#include <cassert>

using namespace std;

#ifdef LOCAL
#include "d:/coding/debug.h"
#else
#define debug(...) 114514
#endif

const int N = 205;
const int M = 1e4 + 5;
int n, m, s, t, cnt, tot;
int head[N], pre_e[N], dis[N], tag[N][N];
bool vis[N], flag;
struct Edge {
    int to, cost, nex;
} e[M];

void add_edge(int u, int v, int w) {
    e[cnt].to = v;
    e[cnt].cost = w;
    e[cnt].nex = head[u];
    head[u] = cnt;
    tag[u][v] = cnt;
    cnt++;
}

void find_augmenting_path(int u) {
    for (int i = head[u]; i != -1; i = e[i].nex) {
        int v = e[i].to, w = e[i].cost;
        if (w == 0 || vis[v]) continue;
        vis[v] = 1;
        pre_e[v] = i;
        dis[v] = min(dis[u], w);
        // debug(u, v, w, dis[v]);
        if (v == t) {
            cerr << "hi\n";
            // debug(u, v, dis[u], w, dis[t]);
            flag = 1;
            return;
        }
        find_augmenting_path(v);
        if (flag) return;
        vis[v] = 0;
    }
}

int temp_cnt;

void update() {
    // assert(0);
    temp_cnt++;
    debug(temp_cnt);
    int now = t;
    while (now != s) {
        int temp = pre_e[now];
        e[temp].cost -= dis[t];
        // debug(dis[t]);
        e[temp ^ 1].cost += dis[t];
        now = e[temp ^ 1].to;
    }
    tot += dis[t];
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    memset(head, -1, sizeof head);
    memset(tag, -1, sizeof tag);
    cin >> n >> m >> s >> t;
    for (int i = 1; i <= m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        if (tag[u][v] != -1) {
            int temp = tag[u][v];
            e[temp].cost += w;
        } else {
            add_edge(u, v, w);
            add_edge(v, u, 0);
        }
    }
    while (1) {
        memset(vis, 0, sizeof vis);
        memset(dis, 0x3f, sizeof dis);
        vis[s] = 1;
        // dis[s] = 0;
        flag = 0;
        find_augmenting_path(s);
        if (!flag) {
            // cerr << "hi\n";
            break;
        } else {
            update();
        }
    }
    cout << tot << '\n';
    return 0;
}

为什么用dfs寻找增广路会在某个地方卡很久 改成用bfs后就过了

2023/12/15 14:20
加载中...