Codeforces Round #725 (Div. 3) C

题目:

You are given an array a of n integers. Find the number of pairs (i,j)(1i<jn)

where the sum of ai+ais greater than or equal to l and less than or equal to r (that is,l≤ai+aj≤r)

t<=1e4,n<=1e5

 

思路:

"It is guaranteed that the sum of n overall test cases does not exceed 2105"

意为一组数据内的n的和不超过2e5

所以时间复杂度可以近似认为是2e5,rather than 2e9!

这时考虑时间复杂度为O(nlogn)的二分查找

 

前置芝士:

 

二分查找

常用于数组和vector

lower_bound(begin(地址),end(地址)的下一个,查找的值),返回>=查找的值的第一个地址

upper_bound(begin,end,查找的值),返回>查找的值的第一个地址

用返回的地址减去首地址即得数组下标

若不存在这样的数返回end

 

code:

for(int i=0;i<n;i++){
  int cntl=lower_bound(a,a+i,L-a[i])-a; 
  int cntr=upper_bound(a+i+1,a+n,R-a[i])-a-i-1;
    ans+=cntr-cntl;
}

 

 

 

 

 

posted @ 2021-06-15 09:09  starlightlmy  阅读(51)  评论(0)    收藏  举报