【水排序】#32 A. Reconnaissance

A. Reconnaissance
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights area1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.

Ways (1, 2) and (2, 1) should be regarded as different.

Input

The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.

Output

Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.

Sample test(s)
input
5 10
10 20 50 60 65
output
6
input
5 1
55 30 29 31 55
output
6

排序后遍历,每个元素向后找m以内差距的元素个数乘二求和

#include <cmath>   
#include <cstdio>  
#include <string>  
#include <cstring>  
#include <iostream>  
#include <algorithm>
using namespace std;
int hgt[1001];
int main()
{
	int n,m,cnt,ans=0;
	cin>>n>>m;
	memset(hgt,0,sizeof hgt);
	for(int i=0;i<n;i++)
	{
		cin>>hgt[i];
	}
	sort(hgt,hgt+n);
	for(int i=0;i<n;i++)
	{
		cnt=0;
		for(int j=i+1; hgt[j]<=hgt[i]+m && j<n; j++ )
		{
			cnt++;
		}
		ans+= 2*cnt;
	}
	printf("%d",ans);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖果天王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值