[ABC421G] Increase to make it Increasing

· · 题解

ABC421G

差分之后要求所有数非负(a_{n + 1} 除外)。每次操作可以让 a_l 加 1,a_{r + 1} 减 1。

怎么看都像是建图题,先 r + 1\to l 连了再说。

对于 a_i < 0 的 i,至少需要 -a_i 次被加 1。而对于 a_i > 0 的 i,至多提供 a_i 次被减 1。将数值看成单位流量,对 a_i > 0,S\to i 连边容量为 a_i。对 a_i < 0,i\to T 连边容量为 -a_i。

特别地,S\to n + 1 连边容量为 +\infty。则有解当且仅当 S\to T 的最大流等于所有 a_i < 0 的 -a_i 之和。为了求出最小操作次数,将 r + 1\to l 的连边的费用设为 1,其余为 0,求最小费用即可。

为什么不用对 a_i > 0 建 i\to T 的边:一是建了之后会影响最大流,二是 a_i 本来就不需要被加 1。如果有这样的流量(i\to T),那么还不如不流。

时间是一次费用流。

#include <bits/stdc++.h>
using namespace std;
constexpr int N = 300 + 5;
constexpr int M = 1e3 + 5;
struct flow {
  int cnt = 1, hd[N], nxt[M << 1], to[M << 1], lim[M << 1], cst[M << 1];
  void add(int u, int v, int w, int c) {
    nxt[++cnt] = hd[u], hd[u] = cnt, to[cnt] = v, lim[cnt] = w, cst[cnt] = c;
    nxt[++cnt] = hd[v], hd[v] = cnt, to[cnt] = u, lim[cnt] = 0, cst[cnt] = -c;
  }
  int fl[N], fr[N], dis[N], vis[N];
  pair<int, int> mincost(int S, int T) {
    int flow = 0, cost = 0;
    while(1) {
      memset(dis, 0x3f, N << 2);
      queue<int> q;
      q.push(S);
      dis[S] = 0, fl[S] = 1e9;
      while(!q.empty()) {
        int t = q.front();
        q.pop(), vis[t] = 0;
        for(int i = hd[t]; i; i = nxt[i]) {
          int it = to[i], d = dis[t] + cst[i];
          if(!lim[i]) continue;
          if(d < dis[it]) {
            dis[it] = d, fr[it] = i;
            fl[it] = min(fl[t], lim[i]);
            if(!vis[it]) {
              vis[it] = 1;
              q.push(it);
            }
          }
        }
      }
      if(dis[T] > 1e9) {
        return make_pair(flow, cost);
      }
      flow += fl[T];
      for(int i = T; i != S; i = to[fr[i] ^ 1]) {
        cost += fl[T] * cst[fr[i]];
        lim[fr[i]] -= fl[T];
        lim[fr[i] ^ 1] += fl[T];
      }
    }
  }
} g;

int n, m, a[N];
int main() {
  cin >> n >> m;
  int S = n + 2, T = 0; 
  for(int i = 1; i <= n; i++) cin >> a[i];
  g.add(S, n + 1, 1e6, 0);
  int tot = 0;
  for(int i = 1; i <= n; i++) {
    if(a[i - 1] < a[i]) {
      g.add(S, i, a[i] - a[i - 1], 0);
    }
    else {
      g.add(i, T, a[i - 1] - a[i], 0);
      tot += a[i - 1] - a[i];
    }
  }
  for(int i = 1; i <= m; i++) {
    int l, r;
    cin >> l >> r, r++;
    g.add(r, l, 1e6, 1);
  }
  auto it = g.mincost(S, T);
  if(it.first != tot) cout << "-1\n";
  else cout << it.second << "\n";
  return 0;
}