列表

详情


NC24945. [USACO 2008 Jan B]Costume Party

描述

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.

输入描述

* Line 1: Two space-separated integers: N and S
* Lines 2..N+1: Line i+1 contains a single integer: Li

输出描述

* 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.

示例1

输入:

4 6
3
5
2
1

输出:

4

说明:

The four pairs are as follows: cow 1 and cow 3; cow 1 and cow 4; cow 2 and cow 4; and finally cow 3 and cow 4.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 215ms, 内存消耗: 608K, 提交时间: 2019-07-28 11:21:25

#include<bits/stdc++.h>
using namespace std;
int main(){
 int n,s,c[20019],ans=0;
 scanf("%d %d",&n,&s);
 for(int i=1;i<=n;i++){
 	  scanf("%d",c+i);
 	  for(int j=1;j<i;j++){
 	  	  if(c[i]+c[j]<=s) ans++; 
	   }
 }
   printf("%d\n",ans);
	 return 0;
}

C++11(clang++ 3.9) 解法, 执行用时: 52ms, 内存消耗: 504K, 提交时间: 2020-02-26 17:11:30

#include<bits/stdc++.h>
using namespace std;
const int M=20005;
int a[M];
int main()
{
	int n,s;
	cin>>n>>s;
	int f=0;
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
		for(int j=0;j<i;j++)
		if(a[i]+a[j]<=s) f++;
	}
	cout<<f<<endl;
	return 0;
}

Python3 解法, 执行用时: 97ms, 内存消耗: 5568K, 提交时间: 2022-05-20 13:44:04

N,S=map(int,input().split())
a=[int(input()) for i in range(N)]
a.sort()
i,j=0,N-1
cnt=0
while i<=N-1 and j>=0 and i<j:
    if a[i]+a[j]>S :
        j-=1
    else :
        cnt+=j-i
        i+=1
print(cnt)

上一题