1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
| #include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long LL;
const LL LINF = 1000000007;
int getint() {
int r = 0, k = 1; char c = getchar();
for (; '0' > c || c > '9'; c = getchar()) if (c == '-') k = -1;
for (; '0' <= c && c <= '9'; c = getchar()) r = r * 10 - '0' + c;
return r * k;
}
struct edge_type {
int to, next;
LL r;
LL c;
} edge[100005];
int S, T, pre[100005], cnte = 1, h[100005], tot;
LL a[100005];
LL dis[100005];
bool vis[100005];
queue<int> Q;
void ins(int u, int v, LL f, LL c) {
edge[++cnte].to = v;
edge[cnte].next = h[u];
h[u] = cnte;
edge[cnte].r = f;
edge[cnte].c = c;
edge[++cnte].to = u;
edge[cnte].next = h[v];
h[v] = cnte;
edge[cnte].r = 0;
edge[cnte].c = -c;
}
bool SPFA(int &flow, LL &cost) {
for (int i = 1; i <= tot; ++i) dis[i] = LINF, vis[i] = false;
pre[S] = 0; dis[S] = 0; vis[S] = true; a[S] = LINF;
Q.push(S);
int now;
while (!Q.empty()) {
now = Q.front(); Q.pop();
vis[now] = false;
for (int i = h[now]; i; i = edge[i].next) {
if (!edge[i].r) continue;
if (dis[edge[i].to] > dis[now] + edge[i].c) {
dis[edge[i].to] = dis[now] + edge[i].c;
a[edge[i].to] = min(a[now], edge[i].r);
pre[edge[i].to] = i;
if (!vis[edge[i].to]) {
vis[edge[i].to] = true;
Q.push(edge[i].to);
}
}
}
}
if (dis[T] == LINF) return false;
flow += a[T];
cost += a[T] * dis[T];
for (now = T; now != S; now = edge[pre[now]^1].to) {
edge[pre[now]].r -= a[T];
edge[pre[now]^1].r += a[T];
}
return true;
}
int n, m, id[100005], tmp;
int main() {
n = getint();
m = getint();
S = ++tot; T = ++tot;
id[0] = ++tot;
for (int i = 1; i <= n; ++i) {
a[i] = getint();
id[i] = ++tot;
}
for (int i = 1; i < n; ++i) {
int d = a[i+1] - a[i];
if (d < 0) { tmp -= d; ins(id[i], T, -d, 0); }
else ins(S, id[i], d, 0);
}
ins(S, id[0], LINF, 0);
ins(S, id[n], LINF, 0);
char str[3];
int l, c;
while (m--) {
scanf("%s", str);
l = getint(); c = getint();
if (str[0] == '-')
for (int i = 0; i + l <= n; ++i)
ins(id[i], id[i+l], LINF, c);
else
for (int i = 0; i + l <= n; ++i)
ins(id[i+l], id[i], LINF, c);
}
int flow = 0;
LL cost = 0;
while (SPFA(flow, cost));
if (flow != tmp) puts("-1");
else printf("%lld", cost);
}
|