Description:
从前往后先读取第一个数字
S1
S
1
,然后顺序向后读入
S1
S
1
个数字。接着再读一个数字
S2
S
2
,顺序向后读入
S2
S
2
个数字
……
…
…
依此类推。只有所有的数恰好读完的序列才是合法的。 给出一个输入序列,可以对于序列中的任意一个数进行修改,使修改后的序列是合法序列。求操作的最小代价。设某个位置但是数是
x
x
,把他变成的代价是
abs(x−y)
a
b
s
(
x
−
y
)
。
Solution:
可以用树状数组做,但是不是很好。
建立最短路模型,每个点连向应该跳到的点,跳到的点向左右连边,代表修改权值,但是不能不合法。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 1e6 + 5;
struct edge {
int nxt, to, w;
} e[maxn * 5];
int n, cnt = 1;
int h[maxn], nxt[maxn], pre[maxn], d[maxn];
void link(int u, int v, int w) {
e[++cnt].nxt = h[u];
h[u] = cnt;
e[cnt].to = v;
e[cnt].w = w;
}
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; ++i) {
int x;
scanf("%d", &x);
for(int j = i; j <= min(i + x + 1, n) && !pre[j]; ++j) {
pre[j] = 1;
link(j, j - 1, 1);
}
for(int j = i + x + 1; j <= n && !nxt[j]; ++j) {
nxt[j] = 1;
link(j, j + 1, 1);
}
if(i + x + 1 <= n + 1) {
link(i, i + x + 1, 0);
} else {
link(i, n + 1, i + x - n);
}
}
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q;
q.push(make_pair(0, 1));
memset(d, 0x3f3f, sizeof(d));
d[1] = 0;
while(!q.empty()) {
pair<int, int> o = q.top();
q.pop();
int u = o.second;
for(int i = h[u]; i; i = e[i].nxt) {
if(d[e[i].to] > d[u] + e[i].w) {
d[e[i].to] = d[u] + e[i].w;
q.push(make_pair(d[e[i].to], e[i].to));
}
}
}
printf("%d\n", d[n + 1]);
return 0;
}