HDU-5178
来源:互联网 发布:js引用 编辑:程序博客网 时间:2024/05/01 06:24
pairs
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2492 Accepted Submission(s): 927
Problem Description
John has n points on the X axis, and their coordinates are (x[i],0),(i=0,1,2,…,n−1) . He wants to know how many pairs<a,b> that |x[b]−x[a]|≤k.(a<b)
Input
The first line contains a single integerT (about 5), indicating the number of cases.
Each test case begins with two integersn,k(1≤n≤100000,1≤k≤109) .
Nextn lines contain an integer x[i](−109≤x[i]≤109) , means the X coordinates.
Each test case begins with two integers
Next
Output
For each case, output an integer means how many pairs<a,b> that |x[b]−x[a]|≤k .
Sample Input
25 5-10001001011025 300-1000100101102
Sample Output
310
题意:在一条数轴上有n个点,给一个数k,求满足两点之间距离小于k的点的对数。
直接用两个for循环枚举会超时,这时需要开动一下脑筋了。当我们从第一个数开始遍历,直到距离大于k,设此时到点pos,那么从第二个数开始遍历时,就可以直接从这个pos位置开始,若满足条件则pos++,否则,ans += pos - i - 1。这样就可以做到一次遍历完成操作。
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int x[100000+50];int main(){ int T, n, k; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &k); for(int i = 0; i < n; i++) scanf("%d", &x[i]); sort(x, x + n); long long ans = 0, pos = 0; for(int i = 0; i < n; i++) { while(x[pos] - x[i] <= k && pos < n) pos++; ans += pos - i - 1; } printf("%lld\n", ans); } return 0;}
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int x[100000+50];int main(){ int T, n, k; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &k); for(int i = 0; i < n; i++) scanf("%d", &x[i]); sort(x, x + n); long long ans = 0, pos = 0;// for(int i = 0; i < n; i++) {// while(x[pos] - x[i] <= k && pos < n) pos++;// ans += pos - i - 1;// } for(int i = 0; i < n; i++) { ans += i - (lower_bound(x, x+n, x[i] - k) - x); // 仔细体会。。。 } printf("%lld\n", ans); } return 0;}
0 0
- hdu 5178
- HDU-5178
- hdu 5178想法题
- HDU 5178 pairs 二分
- HDU - 5178 - pairs
- hdu 5178 二分查找
- hdu 5178 pairs
- hdu 5178 pairs (二分)
- hdu 5178 二分查找
- hdu 5178 pairs
- hdu 5178(尺取法)
- HDU 5178 pairs
- hdu
- hdu
- HDU
- hdu ()
- hdu
- hdu
- IO流_字符缓冲输入流BufferedReader的使用
- 我的第一篇文章在CSDN下诞生了~
- 欢迎使用CSDN-markdown编辑器
- IO流_字符缓冲流复制文本文件案例1
- MVP+Dagger2+Rxjava+Retrofit+GreenDao 开发的小应用,包含新闻、图片、视频3个大模块,代码封装良好
- HDU-5178
- centos6.5安装配置redis3.0
- 函数的调用行为
- UIAlertController的进化
- JSP文件的各个路径的获取
- win10装SCIATRAN辐射传输模式
- zone_reclaimable
- Ubuntu环境下SSH的安装使用以及使用证书免密码登录ssh服务器
- Java容器(七):TreeMap源码分析