费用流-模板

最小费用最大流

#include
#include
#include
#include
#include

#define inf 1000000000
#define MAXN 110
#define MAXM 1010

typedef long long ll;

using namespace std;
 
struct node{
    int from,to,num,cost;
}edge[MAXM],edge1[MAXM];
 
int n,m;
int pn=1;
vectorv[MAXN];
int edgenum=0;
int dis[MAXN],pre[MAXN];
bool vis[MAXN];
 
void link(int x,int y,int z,int d){
    node t;
    t.from=x;
    t.to=y;
    t.num=z;
    t.cost=d;
    edge[edgenum]=t;
    v[x].push_back(edgenum);
    edgenum++;
    t.from=y;
    t.to=x;
    t.num=0;
    t.cost=-d;
    edge[edgenum]=t;
    v[y].push_back(edgenum);
    edgenum++;
} 
 
bool spfa(int s,int e){
	for(int i=1; i<=n; i++)dis[i]=inf;
    memset(vis,0,sizeof(vis));
    dis[s]=0;
    vis[s]=1;
    queueq;
    q.push(s);
    while(!q.empty()){
        int t=q.front();
        q.pop();
        if(t==e)continue;
        for(int i=0; idis[t]+len){
	            dis[to]=dis[t]+len;
	            pre[to]=x;
	            if(!vis[to])q.push(to),vis[to]=1;
            }
        }
        vis[t]=false;
    }
    return dis[e]!=inf;
}

int Maxflow=0,ans=0;

void solve(int s,int e){
    while(spfa(s,e)){
    	int Min=inf;
    	for(int i=e; i!=s; i=edge[pre[i]].from)Min=min(Min,edge[pre[i]].num);
    	for(int i=e; i!=s; i=edge[pre[i]].from)edge[pre[i]].num-=Min,edge[pre[i]^1].num+=Min;
    	Maxflow+=Min;
    	ans+=Min*dis[e];
	}
}

int main(){
	int s,t;
    scanf("%d%d%d%d",&n,&m,&s,&t);
    for(int i=1; i<=m; i++){
    	int x,y,z,d;
    	scanf("%d%d%d%d",&x,&y,&z,&d);
        link(x,y,z,d);
    }
    solve(s,t);
    printf("%d\n",ans);
    
    return 0;
}


你可能感兴趣的:(模板,网络流)