首先考虑 的暴力 dp。
记 表示查找到第 条消息的答案,则初始值为 ,答案为 ,转移方程有:
直接转移可以做到 ,可以得到 的分数。
不妨从另一个角度思考这个问题,我们先把所有 的 取出来拍到数轴上。
我们先默认答案是一步一步走过去的,然后尝试跳跃。注意到我们相当于要在数轴上选择一些不交的区间,然后最大化可节省的步数 。
注意到 的数量 最多只有 ,因此我们只需要在这些“特殊点”上做 dp。
具体地,令 表示考虑了前 个存在引用的消息,且必须选择第 个时,可以节省的最大步数。
为了保证不交,我们必须要求上一次结束的地点在这一次的起点之前,因此有转移方程:
其中 代表第 条消息的位置。
转移时,暴力 无法接受,因此需要二分查找满足要求的最大 。
最终答案就是 再减去最多节省的步数,总时间复杂度 ,可以通过。
参考代码:
#include<bits/stdc++.h>
// #define int long long
#define fo(i, l, r) for(int i = (l); i <= (r); i++)
#define fd(i, l, r) for(int i = (l); i >= (r); i--)
#define fu(i, l, r) for(int i = (l); i < (r); i++)
#define y1 zhang_kevin
#define pii pair<int, int>
#define fi first
#define se second
#define vec vector
#define pb push_back
#define eb emplace_back
#define all(v) v.begin(), v.end()
#define ll long long
#define ull unsigned long long
#define flush() (fwrite(obuf, 1, p3 - obuf, stdout), p3 = obuf)
#define puts wrs
using namespace std;
bool ST;
char ibuf[1 << 20], *p1 = ibuf, *p2 = ibuf, obuf[1 << 20], *p3 = obuf;
inline char gc(){
if(p1 == p2){
p1 = ibuf, p2 = ibuf + fread(ibuf, 1, 1 << 20, stdin);
if(p1 == p2) return EOF;
return *p1++;
}
return *p1++;
}
inline char pc(char ch){
if(p3 == obuf + (1 << 20)) flush();
*p3 = ch;
return *p3++;
}
template<typename type>
inline int rd(type &x){
x = 0; bool f = 0; char ch = gc();
while(!isdigit(ch)) f |= ch == '-', ch = gc();
while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = gc();
return f ? x = -x : 0;
}
template<typename type, typename ...T>
inline void rd(type &x, T &...y){rd(x), rd(y...);}
class Flush{public: ~Flush(){flush();}}_;
template<typename type>
inline void wr(type x){
if(x < 0) pc('-'), x = -x;
if(x > 9) wr(x / 10);
pc(x % 10 + '0');
return;
}
inline void wrs(string s){for(auto ch : s) pc(ch);}
namespace Solution{
const int inf = 2000000000;
int n, q, r[100005], dp[1005], premax[1005];
vec<int> good;
inline void Solve(){
rd(n, q);
fo(i, 1, n){
rd(r[i]);
if(r[i]) good.pb(i);
}
while(q--){
int s, t; rd(s, t); vec<int> nice;
for(auto p : good) if(p <= s && r[p] >= t) nice.pb(p);
int ans = 0;
fu(i, 0, nice.size()){
int rr = r[nice[i]];
int l = 0, r = i - 1, res = -1;
while(l <= r){
int mid = (l + r) >> 1;
if(nice[mid] <= rr){
res = mid;
l = mid + 1;
}else{
r = mid - 1;
}
}
dp[i] = ((nice[i] - rr) - 1) + ((res == -1) ? 0 : premax[res]);
premax[i] = !i ? dp[i] : max(premax[i - 1], dp[i]);
ans = max(ans, dp[i]);
}
wr(s - t - ans), pc('\n');
}
return;
}
}
bool ED;
signed main(){
clock_t START = clock();
// freopen("input.in", "r", stdin), freopen("output.out", "w", stdout);
Solution::Solve();
cerr << (double)(clock() - START) / CLOCKS_PER_SEC << " s" << '\n';
cerr << 1.0 * abs(&ED - &ST) / 1024 / 1024 << " MB" << '\n';
return 0;
}