Description
It’s Halloween! Farmer John is taking the cows to a costume party, but unfortunately he only has one costume. The costume fits precisely two cows with a length of S (1 ≤ S ≤ 1,000,000). FJ has N cows (2 ≤ N ≤ 20,000) conveniently numbered 1…N; cow i has length Li (1 ≤ Li ≤ 1,000,000). Two cows can fit into the costume if the sum of their lengths is no greater than the length of the costume. FJ wants to know how many pairs of two distinct cows will fit into the costume.
Input
- Line 1: Two space-separated integers: N and S
- Lines 2…N+1: Line i+1 contains a single integer: Li
Output
- Line 1: A single integer representing the number of pairs of cows FJ can choose. Note that the order of the two cows does not matter.
Sample Input
4 6
3
5
2
1
Sample Output
4
思路
两两组合,时间复杂度O(n^2),肯定超时。先从大到小排序,遍历每一个,再二分查找后面第一个与之相加小于要求数的数的下标,因为是从大到小排好的,所以这个数后面的所有数都是符合条件的。
代码
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int a[20005];
int main()
{
int n,s;
cin>>n>>s;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a+1,a+n+1,greater<int>());
int ans=0,pos;
for(int i=1;i<n;i++)
{
pos=-1;
int l=i+1,r=n,mid;
while(l<=r)
{
mid=l+(r-l)/2;
if(a[i]+a[mid]<=s)
{
pos=mid;
r=mid-1;
}
else
l=mid+1;
}
if(pos==-1)
continue;
ans=ans+n-pos+1;
}
cout<<ans;
}