0
点赞
收藏
分享

微信扫一扫

HDU5178:pairs(二分法 & 尺取法)


 

pairs
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2497    Accepted Submission(s): 930

Problem Description
John has  points on the X axis, and their coordinates are . He wants to know how many pairs that 
 

Input
The first line contains a single integer  (about 5), indicating the number of cases.
Each test case begins with two integers .
Next  lines contain an integer , means the X coordinates.
 

Output
For each case, output an integer means how many pairs that .
 

Sample Input
2 5 5 -100 0 100 101 102 5 300 -100 0 100 101 102
 

Sample Output
3 10
 

Source
BestCoder Round #31
 

题意:

n个数a[i],问有多少对的差(绝对值)<=k

分析:

暴力枚举每一个数a[i],二分寻找每一个a[i]+k的个数

最近在学习尺取法,说一下这题的尺取做法

尺取法:其实这是一个升序的查找过程,找到了,后面就不可能有了,这样就ok了

#include <iostream>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <sstream>
#define INF 100000000
using namespace std;
typedef long long ll;
const int N=100005;
ll a[N];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n;ll k;
scanf("%d%lld",&n,&k);
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
}
sort(a+1,a+n+1);
ll ans=0;
for(int i=1;i<=n;i++)
{
int pos=upper_bound(a+1+i,a+1+n,a[i]+k)-(a);
ans+=pos-i-1;
}
printf("%lld\n",ans);
}
return 0;
}

# include <stdio.h>
# include <algorithm>
using namespace std;

int a[100001];
int main()
{
int n, k, t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
long long ans = 0;
for(int i=0; i<n; ++i)
scanf("%d",&a[i]);
sort(a, a+n);
for(int l=0,r=1; l<n; ++l)
{
while(r<n && a[r]-a[l]<=k) ++r;
ans += r-l-1;
}
printf("%lld\n",ans);
}
return 0;
}

 

举报

相关推荐

0 条评论