A 小沙の好客
原题链接‘
代码
点击查看代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
#define X first
#define Y second
typedef pair<int,int> pii;
typedef long long LL;
const char nl = '\n';
const int N = 1e6+10;
const int M = 1e6+10;
int n,m;
LL a[N],s[N];
void solve(){
cin >> n >> m;
for(int i = 1; i <= n; i ++){
cin >> a[i];
}
sort(a+1,a+n+1);
for(int i = 1; i <= n; i ++){
s[i] = s[i-1] + a[i];
}
while(m--){
int k,x;
cin >> k >> x;
int l = 1, r = n;
while(l < r){
int mid = l + r + 1 >> 1;
if(a[mid] <= x)l = mid;
else r = mid - 1;
}
if(a[r] > x)cout << 0 << nl;
else cout << s[r] - s[max(0,r-k)] << nl;
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
solve();
}
注意
- 注意二分的性质:二分得到的结果不一定满足要找的点,因此需要加个特判
- 二分找数界限可以用
int j = upper_bound(a+1, a+n+1, x) - a;
- s[max(0,r-k)]不够则取完且防止下标出现负数