网络流学习笔记(1)Dinic算法

//Dinic
#include<bits/stdc++.h>
using namespace std;
struct node{
    int x,y,c,next,other;
}a[2110000];
int len,last[11000],st,ed;
int n,f,d;
void ins(int x,int y,int c){
    len++;int k1 = len;
    a[len].x = x,a[len].y = y,a[len].c = c;
    a[len].next = last[x];
    last[x] = len;
    len++; int k2 = len;
    a[len].x = y,a[len].y = x,a[len].c = 0;
    a[len].next = last[y];
    last[y] = len;
    a[k1].other = k2;
    a[k2].other = k1;
}
queue<int> q;
int h[11000],m;
bool build_h(){ // BFS
    memset(h,0,sizeof(h));
    h[st] = 1;
    q.push(st);
    while(!q.empty()){
        int x = q.front();
        for(int k = last[x];k;k=a[k].next){
            int y = a[k].y;
            if(a[k].c>0&&h[y]==0){
                h[y] = h[x]+1;
                q.push(y);
            }
        }
        q.pop();
    }
    if(h[ed]>0)return 1;
    else return 0;
}
int findflow(int x,int f){ //DFS
    if(x==ed) return f;
    int s = 0,t;
    for(int i = last[x];i;i=a[i].next){
        int y = a[i].y;
        if(a[i].c>0&&h[y]==(h[x]+1)&&s<f){
            s+=(t = findflow(y,min(a[i].c,f-s)));
            a[i].c -= t;a[a[i].other].c+=t;
        }
    }
    if(s==0)h[x] = 0;
    return s;
}
int main(){
    scanf("%d%d%d%d",&n,&m,&st,&ed);
    len = 0;
    memset(last,0,sizeof(last));
    int s = 0,t;
    
    int ai,bi,ci;
    for(int i = 1;i<=m;i++){
        scanf("%d%d%d",&ai,&bi,&ci);
        ins(ai,bi,ci);
    }
    while(build_h()){
        s+=findflow(st,99999999);
    }
    printf("%d\n",s);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/LJA001100/p/10360469.html