POJ 3663 Costume Party (two points)

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

Ideas

Pairwise combination, time complexity O(n^2), definitely overtime. Sort from largest to smallest, traverse each one, and then find the first subscript that adds to the number less than the required number. Because it is sorted from largest to smallest, all the numbers after this number are eligible.

Code

#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;
}

Guess you like

Origin blog.csdn.net/m0_54621932/article/details/113998877