首页 > 编程语言 >A 小沙の好客【2023牛客寒假算法基础集训营5】

A 小沙の好客【2023牛客寒假算法基础集训营5】

时间:2023-02-01 22:36:10浏览次数:51  
标签:二分 include const int 牛客 小沙 好客 集训营

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();
}

注意

  1. 注意二分的性质:二分得到的结果不一定满足要找的点,因此需要加个特判
  2. 二分找数界限可以用int j = upper_bound(a+1, a+n+1, x) - a;
  3. s[max(0,r-k)]不够则取完且防止下标出现负数

标签:二分,include,const,int,牛客,小沙,好客,集训营
From: https://www.cnblogs.com/J-12045/p/17084314.html

相关文章