zoukankan      html  css  js  c++  java
  • SPFA费用流模板

    #include<bits/stdc++.h>  
    //#pragma comment(linker, "/STACK:1024000000,1024000000")   
    #include<stdio.h>  
    #include<algorithm>  
    #include<queue>  
    #include<string.h>  
    #include<iostream>  
    #include<math.h>  
    #include<set>  
    #include<map>  
    #include<vector>  
    #include<iomanip>  
    using namespace std;  
    #define ll long long  
    #define pb push_back  
    #define FOR(a) for(int i=1;i<=a;i++)  
    const int inf=0x3f3f3f3f;  
    const int maxn=4e5+9;    
      
    struct EDGE{  
        int to,next,cap,flow,cost;  
    }G[maxn];  
    int head[maxn],tot;  
    int pre[maxn],dis[maxn];  
    int vis[maxn];  
      
    int source,sink;  
    int num_nodes;  
      
    void init(){  
        tot=0;  
        memset(head,-1,sizeof head);  
    }  
    void addedge(int u,int v,int cap,int cost){  
        G[tot]=(EDGE){v,head[u],cap,0,cost};head[u]=tot++;  
        G[tot]=(EDGE){u,head[v],0,0,-cost} ;head[v]=tot++;  
    }  
    int spfa(int s,int t){  
        queue<int>Q;  
        for(int i=0;i<=num_nodes;i++){dis[i]=inf;vis[i]=0;pre[i]=-1;}  //偶尔要根据点的标记顺序修改一下
        dis[s]=0;vis[s]=1;  
        Q.push(s);  
        while(!Q.empty()){  
            int u=Q.front();Q.pop();vis[u]=0;  
            for(int i=head[u];~i;i=G[i].next){  
                int v=G[i].to;  
                if(G[i].cap>G[i].flow && dis[v]>dis[u]+G[i].cost){  
                    dis[v]=dis[u]+G[i].cost;  
                    pre[v]=i;  
                    if(!vis[v]){  
                        vis[v]=1;  
                        Q.push(v);  
                    }  
                }  
            }  
        }  
        if(pre[t]==-1)return 0;  
        return 1;  
    }  
    int mcmf(int &cost){  
        int s=source,t=sink;  
        int flow=0;  
        cost=0;  
        while(spfa(s,t)){  
            int a=inf;  
            for(int i=pre[t];~i;i=pre[G[i^1].to]){  
                a=min(a,G[i].cap-G[i].flow);  
            }  
            for(int i=pre[t];~i;i=pre[G[i^1].to]){  
                G[i].flow+=a;  
                G[i^1].flow-=a;  
                cost+=G[i].cost*a;  
            }  
            flow+=a;  
        }  
        return flow;  
    }
    /*******
    init,num_nodes,source,sink
    *******/
    


  • 相关阅读:
    Android 自定义标题栏 并进行事件处理
    java synchronized详解
    Java中LinkedList与ArrayList有什么区别
    android动态全屏切换
    java线程机制介绍
    设置导航栏背景和文字属性
    Dictionary的用法
    bundle
    解析Json
    Copy与MutableCopy
  • 原文地址:https://www.cnblogs.com/Drenight/p/8611312.html
Copyright © 2011-2022 走看看