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
    *******/
    


  • 相关阅读:
    myfocus之焦点图
    win7磁盘分区工具
    java线程两种创建方式的区别与模拟买票情景
    jsp指令与动作
    Cookie记住登陆账号和密码
    jsp+javabean实现简单的用户登陆
    jsp简单登陆实现
    strut2 文件上传完整案例
    poi 导出excel文件
    poi excel文件的导入
  • 原文地址:https://www.cnblogs.com/Drenight/p/8611312.html
Copyright © 2011-2022 走看看