UVa 1658

题目链接:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=0&problem=4533&mosmsg=Submission+received+with+ID+26558714

点容量:拆点,连一条容量为 (1) 费用为 (0) 的边

跑容量为 (2) 的最小费用流即可

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn = 50010; 
const int INF = 1000000007;

int n, m;

int h[maxn], cnt = 0;
struct E{
	int from, to, cost, cap, next;
}e[maxn << 1];
void add(int u, int v, int w, int c){
	e[++cnt].to = v;
	e[cnt].from = u;
	e[cnt].cap = c;
	e[cnt].cost = w;
	e[cnt].next = h[u];
	h[u] = cnt;
}

  int inq[maxn];         // 是否在队列中
  int d[maxn];           // Bellman-Ford
  int p[maxn];           // 上一条弧
  int a[maxn];           // 可改进量
  bool BellmanFord(int s, int t, int flow_limit, int& flow, int& cost) {
    memset(d, 0x3f, sizeof(d));
    memset(inq, 0, sizeof(inq));
    memset(a, 0, sizeof(a));
    d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;

    queue<int> Q;
    Q.push(s);
    while(!Q.empty()) {
      int u = Q.front(); Q.pop();
      inq[u] = 0;
      for(int i = h[u]; i != -1 ; i = e[i].next) {
        if(e[i].cap && d[e[i].to] > d[u] + e[i].cost) {
          d[e[i].to] = d[u] + e[i].cost;
          p[e[i].to] = i;
          a[e[i].to] = min(a[u], e[i].cap);
          if(!inq[e[i].to]) { Q.push(e[i].to); inq[e[i].to] = 1; }
        }
      }
    }
    if(d[t] == INF) return false;
    if(flow + a[t] > flow_limit) a[t] = flow_limit - flow;
    flow += a[t];
    cost += d[t] * a[t];
    for(int u = t; u != s; u = e[p[u]].from) {
      e[p[u]].cap -= a[t];
      e[p[u]^1].cap += a[t];
    }
    return true;
  }

  // 需要保证初始网络中没有负权圈
  int MincostFlow(int s, int t, int flow_limit, int& cost) {
    int flow = 0; cost = 0;
    
    while(flow < flow_limit && BellmanFord(s, t, flow_limit, flow, cost));
    return flow;
  }

ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }

int main(){
	while(scanf("%d%d", &n, &m) == 2 && n) {
		memset(h, -1, sizeof(h)); cnt = 1;
		
		for(int i = 2 ; i <= n - 1 ; ++i){ // 拆点 
			add(i, i + n, 0, 1);
			add(i + n, i, 0, 0);
		}
		
		int u, v, w;
		for(int i = 1 ; i <= m ; ++i){ // 连边 
			scanf("%d%d%d", &u, &v, &w);
			
			if(u != 1 && u != n) u += n;
			
			add(u, v, w, 1); // 出点连入点 
			add(v, u, -w, 0);
		}
		
		int cost = 0;
		
		MincostFlow(1, n, 2, cost);
		
		printf("%d
", cost);		
	}
	
	return 0;
}
原文地址:https://www.cnblogs.com/tuchen/p/14995334.html