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,,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 integerT (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
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;}

还有一种做法是用二分查找,可以从0开始遍历,到i位置查找之前中距离小于等于k的点数。
#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
原创粉丝点击