pairs

pairs

http://acm.hdu.edu.cn/showproblem.php?pid=5178

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4888    Accepted Submission(s): 1758


Problem Description
John has  n points on the X axis, and their coordinates are (x[i],0),(i=0,1,2,,n1). He wants to know how many pairs<a,b> that |x[b]x[a]|k.(a<b)
 
Input
The first line contains a single integer  T (about 5), indicating the number of cases.
Each test case begins with two integers n,k(1n100000,1k109).
Next n lines contain an integer x[i](109x[i]109), means the X coordinates.
 
Output
For each case, output an integer means how many pairs <a,b> that |x[b]x[a]|k.
 
Sample Input
2
5 5
-100
0
100
101
102
5 300
-100
0
100
101
102
 
Sample Output
3
10
 
Source
 
Recommend
hujie   |   We have carefully selected several similar problems for you:   6447  6446  6445  6444  6443 
 

二分水题

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <string>
 4 #include <cmath>
 5 #include <iostream>
 6 #include <algorithm>
 7 #include <queue>
 8 #include <stack>
 9 #include <vector>
10 #include <set>
11 #include <map>
12 typedef long long ll;
13 #define maxn 100005
14 #define lson l,mid,rt<<1
15 #define rson mid+1,r,rt<<1|1
16 using namespace std;
17 
18 
19 ll n,k;
20 ll a[maxn];
21 
22 int main(){
23 
24     int T;
25     while(cin>>T){
26         while(T--){
27             cin>>n>>k;
28             for(int i=1;i<=n;i++){
29                 cin>>a[i];
30             }
31             sort(a+1,a+n+1);
32             ll ans=0;
33             int p;
34             for(int i=2;i<=n;i++){
35                 p=lower_bound(a+1,a+i,a[i]-k)-a;
36                 ans+=i-p;
37             }
38 
39             cout<<ans<<endl;
40         }
41     }
42 
43 }
View Code

猜你喜欢

转载自www.cnblogs.com/Fighting-sh/p/10073609.html