题解:P15804 [GESP202603 八级] 消息查找
堆+线性dp
#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 1000050;
struct Node{
long long x,y;
};
struct node{
long long x,y;
bool operator < (const node &temp) const {
return this->x > temp.x;
}
};
Node data1[MAXN],number;
long long t = 1,n,m,data2[MAXN],ans,pos,l,r,mid,temp,start,pre;
long long length,x,y;
inline bool compare(const Node &x,const Node &y);
inline long long search(long long x);
inline long long query(long long x,long long y,long long z);
inline void solve();
int main(){
//ios_base::sync_with_stdio(false);
//cin.tie(nullptr);
//cout.tie(nullptr);
while (t --){
solve();
}
return 0;
}
inline bool compare(const Node &x,const Node &y){
if (x.x != y.x){
return x.x < y.x;
} else {
return x.y < y.y;
}
}
inline long long search(long long x){
ans = -1;
l = 1;
r = length;
while (l <= r){
mid = (l + r) >> 1;
if (data1[mid].x >= x){
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
inline long long query(long long x,long long y,long long z){
if (z == -1){
return 0;
}
priority_queue<node> q;
q.push((node){x,0});
pre = temp = 0;
for (long long i = z;i <= length;i ++){
if (data1[i].x > y){
break;
}
if (data1[i].y > y){
continue;
}
while (!q.empty() && q.top().x <= data1[i].x){
temp = max(temp,q.top().y);
q.pop();
}
q.push((node){data1[i].y,temp + data1[i].y - data1[i].x - 1});
pre = max(pre,temp + data1[i].y - data1[i].x - 1);
}
return pre;
}
inline void solve(){
cin >> n >> m;
for (long long i = 1;i <= n;i ++){
cin >> data2[i];
}
for (long long i = 2;i <= n;i ++){
if (data2[i]){
data1[++length].x = data2[i];
data1[length].y = i;
}
}
sort(data1 + 1,data1 + 1 + length,compare);
for (long long i = 1;i <= m;i ++){
cin >> x >> y;
swap(x,y);
pos = search(x);
cout << y - x - query(x,y,pos) << endl;
}
return ;
}