Codeforces 474E - Pillars

时间:2024-08-05 12:37:02

一眼看上去非常像最长不下降子序列。

然后比赛的时候对每个答案长度为k的序列,维护最后一个数的最大值和最小值。

当时不知道为什么认为从长度最长倒推至前面不会太长,于是心满意足地敲了个O(n^2)。结果T了。。。

正确的做法应该用线段树维护,搜起来就是log(n),总的就是O(N*logN);

用非递归的方法写的

只用了77ms

#include <iostream>
#include <cstdio>
using namespace std; #define ll long long const int INF = ; struct node {
ll key;
int pos;
} dtmin[INF], dtmax[INF];
ll n, d, t, x, M;
ll pre[INF];
int f[INF], ans[INF], namax[INF], namin[INF]; inline int Searchmax (int x, ll k) {
while (dtmax[x].key - k >= d) {
if (x > M) return dtmax[x].pos;
if (dtmax[x << | ].key - k >= d) x = x << | ;
else
x = x << ;
}
return ;
}
inline int Searchmin (int x, ll k) {
while (k - dtmin[x].key >= d) {
if (x > M) return dtmin[x].pos;
if (k - dtmin[x << | ].key >= d) x = x << | ;
else
x = x << ;
}
return ;
} inline void modify (int x, ll k, int i) {
if (dtmax[x + M].key < k) namax[x] = i, dtmax[x + M].key = k;
for (int t = x + M; dtmax[t >> ].key < k && t > ; t >>= )
dtmax[t >> ] = dtmax[t]; if (dtmin[x + M].key > k) namin[x] = i, dtmin[x + M].key = k;
for (int t = x + M; dtmin[t >> ].key > k && t > ; t >>= )
dtmin[t >> ] = dtmin[t];
} int main() {
ios::sync_with_stdio (false);
cin >> n >> d;
cin>>x;
M = n;
int tem = ;
for (int k = M; k; tem++, k >>= ) ;
M = << tem;
for (int i = ; i < (M << ) + ; i++) {
dtmax[i].key = , dtmin[i].key = (1LL << );
dtmax[i].pos = i - M, dtmin[i].pos = i - M;
}
dtmax[].key = dtmin[].key = x;
t = f[] = ;
modify (t, x, );
for (int i = ,k; i <= n; i++) {
cin >> x;
if (k = Searchmax (, x) )
if (f[i] < k + )
f[i] = k + , pre[i] = namax[k]; if ((k = Searchmin (, x)))
if (f[i] < k + )
f[i] = k + , pre[i] = namin[k]; if (f[i] > t) t = f[i];
if (f[i] == ) f[i] = ;
modify (f[i], x, i);
}
cout << t << endl;
int p = -;
for (int i = ; i <= n; i++) if (f[i] == t) { p = i; break; }
for (int i = t; i; i--)
ans[i] = p, p = pre[p];
for (int i = ; i <= t; i++)
cout << ans[i] << ' ';
}