羅区-3381 [テンプレート]最小コスト最大

タイトル説明
したように、ネットワーク図が与えられ、ソース及びシンクは、各側部ユニットは最大流量の場合には最大流量と最小コストネットワークを決定する最大流量とトラフィック電荷を、知られています。
入力フォーマットが
最初の行は、4つの正の整数N、M、S、Tを含み、それぞれ、エッジの数、ソースポイント番号、シリアル番号シンクとの点の数。
次のMラインは、4つの整数UI、VI、WI、Fiが含まれてそこからエッジまでのUI i番目を示し、単位流量当たり、VI、WIの右側(最大流量のWiの、すなわち、側)に到着します手数料Fiを提供しています。
フォーマット出力
最大流量条件で最大流量と最小コストに続く2つの整数を含む1行。

サンプル入力出力
入力#1
。4 3 5 4
4 2 30 2
4 3 20である。3
2 3 1 20
2 30 9 1
。1 5 40 3

出力#1
50 280

説明/ヒント
スペースの制約:1000ミリ秒、128M
(BYX:1200msに最後の二つの点)
のデータサイズ:
データの30%:N <= 10、M < = 10
データの70%:N <= 1000、 M <= 1000
データの100%まで:N <= 5000、M < = 50000

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=100010;
bool vis[maxn];
int n,m,s,t,x,y,z,f,dis[maxn],pre[maxn],last[maxn],flow[maxn],maxflow,mincost;
struct Edge{
    int to,next,flow,dis;
}edge[maxn];
int head[maxn],num_edge;
queue <int> q;
void add_edge(int from,int to,int flow,int dis){
    edge[++num_edge].next=head[from];
    edge[num_edge].to=to;
    edge[num_edge].flow=flow;
    edge[num_edge].dis=dis;
    head[from]=num_edge;
}
bool spfa(int s,int t){
    memset(dis,0x7f,sizeof(dis));
    memset(flow,0x7f,sizeof(flow));
    memset(vis,0,sizeof(vis));
    q.push(s); vis[s]=1; dis[s]=0; pre[t]=-1;
    while (!q.empty()){
        int now=q.front();
        q.pop();
        vis[now]=0;
        for (int i=head[now]; i!=-1; i=edge[i].next){
            if(edge[i].flow>0 && dis[edge[i].to]>dis[now]+edge[i].dis){
                dis[edge[i].to]=dis[now]+edge[i].dis;
                pre[edge[i].to]=now;
                last[edge[i].to]=i;
                flow[edge[i].to]=min(flow[now],edge[i].flow);
                if (!vis[edge[i].to]){
                    vis[edge[i].to]=1;
                    q.push(edge[i].to);
                }
            }
        }
    }
    return pre[t]!=-1;
}
void MCMF(){
    while (spfa(s,t)){
        int now=t;
        maxflow+=flow[t];
        mincost+=flow[t]*dis[t];
        while (now!=s){
            edge[last[now]].flow-=flow[t];
            edge[last[now]^1].flow+=flow[t];
            now=pre[now];
        }
    }
}
int main(){
    memset(head,-1,sizeof(head)); num_edge=-1;
    scanf("%d%d%d%d",&n,&m,&s,&t);
    for (int i=1; i<=m; i++){
        scanf("%d%d%d%d",&x,&y,&z,&f);
        add_edge(x,y,z,f); add_edge(y,x,0,-f);
    }
    MCMF();
    printf("%d %d",maxflow,mincost);
    return 0;
}

おすすめ

転載: blog.csdn.net/mkopvec/article/details/91906780