ISAP TLE求调

P3376 【模板】网络最大流

qige_mingzi @ 2023-12-22 20:01:59

rt,TLE on # 9, #10

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,s,t;
const int maxn = 5000;
int head[maxn<<1],nex[maxn<<1],to[maxn<<1],cap[maxn<<1],flow[maxn<<1],cnt = 1;
const int INF = 1e18;
void add(int u,int v,int w1,int w2){
    nex[++cnt] = head[u];
    head[u] = cnt;
    to[cnt] = v;
    cap[cnt] = w1;
    flow[cnt] = w2;
} 
queue<int> q;
int ans;
int h[maxn],num[maxn],pre[maxn];
void make_high(){
    memset(h,-1,sizeof(h));
    h[t] = 0;
    num[0]++;//±ðÍüÁË£¡ 
    q.push(t);
    while(!q.empty()){
        int r = q.front();
        q.pop();
        for(int i = head[r];i;i = nex[i]){
            //cout << h[3] << " ";
            if(cap[i] == 0&&h[to[i]] == -1){
                h[to[i]] = h[r]+1;
                num[h[to[i]]]++;
                q.push(to[i]);
            }
        }
    }
}
void ISAP(){
    if(h[s] >= n){
        return;
    }
    int x = s;
    int d = INF;
    bool b = false;
    while(h[s] < n){
        x = s;
        d = INF;
        /*for(int i = 1;i <= n;i++){
            cout << h[i] << " ";
        }*/
        //cout << endl;
        while(x != t){
            b = false;
            for(int i = head[x];i;i = nex[i]){
                if(cap[i] > flow[i]&&h[x] > h[to[i]]){
                    d = min(d,cap[i]-flow[i]);
                    pre[to[i]] = i;
                    x = to[i];
                    b = true;
                    break;
                }
            }
            if(b == false){
                int hm = INF;
                for(int i = head[x];i;i = nex[i]){
                    if(cap[i] > flow[i]){
                        hm = min(hm,h[to[i]]);//×¢ÒâÕâÀïÊÇ×îСֵ 
                    }
                }
                if(num[h[x]] == 1){
                    return;
                }
                num[h[x]]--;
                if(hm == INF){
                    h[x] = n;
                }
                else{
                    h[x] = hm+1;    
                }
                //h[x]++;
                num[h[x]]++;
                break;
            }
        }
        if(x == t){
            ans += d;
            for(int i = pre[t];i;i = pre[to[i^1]]){
                flow[i] += d;
                flow[i^1] -= d;
            }
        }
    }
}
signed main()
{
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    cin >> n >> m >> s >> t;
    int u,v,w;
    for(int i= 1;i <= m;i++){
        scanf("%lld%lld%lld",&u,&v,&w);
        add(u,v,w,0);
        add(v,u,0,0);
    }
    make_high();
    ISAP();
    cout << ans << endl;
    return 0;
}
/*
Author: qige_mingzi
Start thinking at
Start coding at
Finish coding at
Finish debugging at
*/

|