XK Segments 二分

5327: XK Segments

时间限制: 1 Sec   内存限制: 256 MB
提交: 105   解决: 28
[ 提交][ 状态][ 讨论版][命题人: admin]

题目描述

While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i, j) such that ai ≤ aj and there are exactly k integers y such that ai ≤ y ≤ aj and y is divisible by x.

In this problem it is meant that pair (i, j) is equal to (j, i) only if i is equal to j. For example pair (1, 2) is not the same as (2, 1).

输入

The first line contains 3 integers n, x, k (1 ≤ n ≤ 105, 1 ≤ x ≤ 109, 0 ≤ k ≤ 109), where n is the size of the array a and x and k are numbers from the statement.

The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

输出

Print one integer — the answer to the problem.

样例输入

4 2 1
1 3 5 7

样例输出

3

提示

In first sample there are only three suitable pairs of indexes — (1, 2), (2, 3), (3, 4).
In second sample there are four suitable pairs of indexes(1, 1), (2, 2), (3, 3), (4, 4).

In third sample every pair (i, j) is suitable, so the answer is 5 * 5 = 25.

对数组排序,对每个ai计算aj的最小值与最大值

最小值:((ai1)/x+k)*x 因为可能会比x小,所以与x取较大值

最大值:((ai-1)/x+k+1)*x

然后使用lower_bound函数找到第一个大于等于的数的位置,相减即为ai的方案数

最后用long long保存总结果

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD=1e9+7;
const int INF=1e5+100;
ll a[INF];
int main()
{
    ll n,x,k;
    cin>>n>>x>>k;
    for(int i=0; i<n; i++){
        cin>>a[i];
    }
    sort(a,a+n);
    ll ans=0;
    for(int i=0; i<n; i++){
        ll s=max(a[i],((a[i]-1)/x+k)*x);
        ll e=(((a[i]-1)/x+k+1)*x);
        ans+=lower_bound(a,a+n,e)-lower_bound(a,a+n,s);
    }
    cout<<ans<<endl;
    return 0;
}



扫描二维码关注公众号,回复: 2301790 查看本文章

猜你喜欢

转载自blog.csdn.net/renzijing/article/details/80428190