SAP解决USACO4.2.1网络流问题

/*
ID: hk945801
TASK: ditch
LANG: C++
*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int a[201][201],pre[201],level[201],gap[201];
int main(){
    int i,j,k,m,n;
    freopen("ditch.in","r",stdin);
    freopen("ditch.out","w",stdout);
    cin>>m>>n;
    for(i=1;i<=m;i++){
    	int x,y,z;
        cin>>x>>y>>z;
        a[x][y]+=z;
    }
    int s=1;
    gap[0]=n;
    int v,p=pre[s]=s;
	int ans=0,sum;
    while(level[s]<n){
        for(v=1;v<=n;v++){
            if(a[p][v]>0 && level[p]==level[v]+1){
                break;
            }
        }
        if(v<=n){
            pre[v]=p;
            p=v;
            if(v==n){
                sum=1000000001;
                for(i=v;i!=s;i=pre[i]){
                    if(sum>a[pre[i]][i])sum=a[pre[i]][i];
                }
                ans+=sum;
                for(i=v;i!=s;i=pre[i]){
                    a[pre[i]][i]-=sum;
                    a[i][pre[i]]+=sum;
                }
                p=s;
            }
        }else {
            int min=n;
            for(v=1;v<=n;v++){
                if(a[p][v]>0 && min>level[v]){
                    min=level[v];
                }
            }
            gap[level[p]]--;
            if(gap[level[p]]==0)break;
            level[p]=min+1;
            gap[level[p]]++;
            p=pre[p];
        }
    }
    cout<<ans<<endl;
    return 0;
}

你可能感兴趣的:(C语言,SAP,USACO,网络流)