• CodeForces 362E Petya and Pipes


    Description

    给一个 (n) 个点的网络流图,每次可以让一条边的最大流量增加 (1) ,最多 (k) 次,求最大流量。

    (nle 50,0le kle 10^3)

    Solution

    把原图每条边 ((u,v,c)) 拆成两条代费用的边 ((u,v,c,0))((u,v,k,1)) ,增广到费用大于 (k) 为止。

    #include<bits/stdc++.h>
    using namespace std;
    
    template <class T> void read(T &x) {
    	x = 0; bool flag = 0; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) flag |= ch == '-';
    	for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - 48; flag ? x = ~x + 1 : 0;
    }
    
    #define N 51
    #define rep(i, a, b) for (int i = (a); i <= (b); i++)
    #define INF 0x3f3f3f3f
    
    int k;
    
    int flow, cost, head[N], tot = 1, dis[N], pre[N];
    struct { int v, c, w, next; }e[100010];
    queue<int> q;
    bool inq[N];
    inline void insert(int u, int v, int c, int w) {
    	e[++tot].v = v, e[tot].c = c, e[tot].w = w, e[tot].next = head[u], head[u] = tot;
    }
    inline void add(int u, int v, int c, int w) {
    	insert(u, v, c, w), insert(v, u, 0, -w);
    }
    bool spfa(int S, int T) {
    	memset(dis, 0x3f, sizeof dis); dis[S] = 0, q.push(S);
    	while (!q.empty()) {
    		int u = q.front(); q.pop(), inq[u] = 0;
    		for (int i = head[u], v; i; i = e[i].next) e[i].c && dis[v = e[i].v] > dis[u] + e[i].w ?
    			dis[v] = dis[u] + e[i].w, pre[v] = i, (!inq[v] ? q.push(v), inq[v] = 1 : 0) : 0;
    	}
    	if (dis[T] >= INF) return 0;
    	int d = INF;
    	for (int i = T; i != S; i = e[pre[i] ^ 1].v) d = min(d, e[pre[i]].c);
    	if (cost + d * dis[T] > k) {
    		flow += (k - cost) / dis[T];
    		return 0;
    	}
    	return 1;
    }
    void mcf(int S, int T) {
    	int d = INF;
    	for (int i = T; i != S; i = e[pre[i] ^ 1].v) d = min(d, e[pre[i]].c);
    	for (int i = T; i != S; i = e[pre[i] ^ 1].v) e[pre[i]].c -= d, e[pre[i] ^ 1].c += d, cost += d * e[pre[i]].w;
    	flow += d;
    }
    
    int main() {
    	int n; read(n), read(k);
    	rep(i, 1, n) rep(j, 1, n) {
    		int f; read(f);
    		if (f) add(i, j, f, 0), add(i, j, k, 1);
    	}
    	int ans = 0;
    	while (spfa(1, n)) mcf(1, n);
    	cout << flow;
    	return 0;
    }
    
  • 相关阅读:
    CF 640(div4)
    ABC 166
    CF 637 div2
    HDU-1875 畅通工程再续
    POJ1251-Jungle Roads
    POJ1797 Heavy Transportation
    Gym-101911K Medians and Partition
    Gym-101911A Coffee Break
    【Vue】Re09 Webpack 第一部分(介绍、安装、配置)
    【Vue】Re08 模块化
  • 原文地址:https://www.cnblogs.com/aziint/p/9609720.html
Copyright © 2020-2023  润新知