zoukankan      html  css  js  c++  java
  • luogu2153 [SDOI2009]晨跑

    要想限制流量,总要想着拆点。

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <queue>
    using namespace std;
    int n, m, ss, tt, uu, vv, ww, maxFlow, minCost, cnt, hea[405], pre[405];
    int dis[405];
    const int oo=0x3f3f3f3f;
    queue<int> d;
    bool vis[405];
    struct Edge{
    	int too, nxt, val, cst;
    }edge[50005];
    void add_edge(int fro, int too, int val, int cst){
    	edge[cnt].nxt = hea[fro];
    	edge[cnt].too = too;
    	edge[cnt].val = val;
    	edge[cnt].cst = cst;
    	hea[fro] = cnt++;
    }
    void addEdge(int fro, int too, int val, int cst){
    	add_edge(fro, too, val, cst);
    	add_edge(too, fro, 0, -cst);
    }
    bool bfs(){
    	memset(pre, -1, sizeof(pre));
    	memset(dis, 0x3f, sizeof(dis));
    	dis[ss] = 0;
    	d.push(ss);
    	vis[ss] = true;
    	while(!d.empty()){
    		int x=d.front();
    		d.pop();
    		vis[x] = false;
    		for(int i=hea[x]; i!=-1; i=edge[i].nxt){
    			int t=edge[i].too;
    			if(dis[t]>dis[x]+edge[i].cst && edge[i].val>0){
    				pre[t] = i;
    				dis[t] = dis[x] + edge[i].cst;
    				if(!vis[t]){
    					vis[t] = true;
    					d.push(t);
    				}
    			}
    		}
    	}
    	return dis[tt]!=oo;
    }
    void dinic(){
    	while(bfs()){
    		int tmp=oo;
    		for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too])
    			tmp = min(tmp, edge[i].val);
    		for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too]){
    			edge[i].val -= tmp;
    			edge[i^1].val += tmp;
    			minCost += tmp * edge[i].cst;
    		}
    		maxFlow += tmp;
    	}
    }
    int main(){
    	memset(hea, -1, sizeof(hea));
    	cin>>n>>m;
    	ss = 1; tt = n * 2;
    	for(int i=1; i<=n; i++)
    		if(i!=1 && i!=n)	addEdge(i, i+n, 1, 0);
    		else	addEdge(i, i+n, oo, 0);
    	for(int i=1; i<=m; i++){
    		scanf("%d %d %d", &uu, &vv, &ww);
    		addEdge(uu+n, vv, 1, ww);
    	}
    	dinic();
    	cout<<maxFlow<<" "<<minCost<<endl;
    	return 0;
    }
    
  • 相关阅读:
    [湖北省队互测2014] 没有人的算术 (非题解)
    普及常见图论算法整理
    普及常见数据结构板子整理
    Pisano Period
    退役了
    LOJ3246 「USACO 2020.1 Platinum」Cave Paintings
    LOJ3193 「ROI 2019 Day2」机器人高尔夫球赛
    LOJ3192 「ROI 2019 Day2」课桌
    LOJ6496 「雅礼集训 2018 Day1」仙人掌
    Luogu P4518 [JSOI2018]绝地反击
  • 原文地址:https://www.cnblogs.com/poorpool/p/8182063.html
Copyright © 2011-2022 走看看