题解:AT_abc440_d [ABC440D] Forbidden List 2
题目传送门(Luogu)
题目传送门(AtCoder)
我很纳闷为什么几乎没有什么人写时间复杂度
关于我 lower_bound 神奇写成 upper_bound 硬控我一个小时的奇葩事件。
思路
观察题意,大概就是在
我们先将输入的数组
然后我们将 lower_bound 而不是手写二分),然后再在
我们现在可以证明为什么上文中提到的特判可以不做。因为如果
细节请看代码,在我看来还是比较短小精悍的。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
long long s[N], cnt[N], pfx[N];
int n, q;
void solve()
{
int x, y;
cin >> x >> y;
auto it = lower_bound(s + 1, s + n + 1, x);
int idx = it - s;
int temp = y;
temp -= *it - x;
// if(temp <= 0)
// {
// cout << x + y - 1 << "\n";
// return ;
// } 可以不做这个特判
temp += pfx[idx - 1];
it = lower_bound(pfx, pfx + n + 1, temp);
int cur = it - pfx;
cout << x + y + cur - idx << "\n";
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> q;
for(int i = 1; i <= n; i++)cin >> s[i];
sort(s + 1, s + n + 1);
s[n + 1] = 1e18;
for(int i = 1; i <= n; i++)cnt[i] = s[i + 1] - s[i] - 1;
for(int i = 1; i <= n; i++)cnt[i] = max(cnt[i], 0ll);
pfx[0] = cnt[0];
for(int i = 1; i <= n; i++)pfx[i] = cnt[i] + pfx[i - 1];
while(q--)solve();
return 0;
}