[ABC421G] Increase to make it Increasing
ABC421G
差分之后要求所有数非负(
怎么看都像是建图题,先
对于
特别地,
为什么不用对
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;
}