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.
排序后用二分查找解决
对于每个a[i],可以根据他的值,算出满足a[i]~a[j]中有k个x的倍数的a[j]的范围,然后二分查找数组求出对数
#include<bits/stdc++.h> using namespace std; typedef long long LL; #define SIZE 100005 LL n,k,x,res = 0; LL a[SIZE]; int main(){ // freopen("test.in","r",stdin); ios::sync_with_stdio(false); cin >> n >> x >> k; for (int i=0;i<n;i++){ cin >> a[i]; } sort(a,a+n); // now = t * x,up = (t+k)*x-1,down = (t+k-1)*x // now = t * x,up = t*x - 1,down = (t-1)*x // now = t * x + b up = (t+k+1)*x - 1,down = (t+k)*x for (int i=0;i<n;i++){ LL now = a[i],up,down; if (now % x == 0){ if (k == 0) continue; up = (now/x+k)*x - 1; down = max((now/x+k-1)*x,a[i]); } else { up = (now/x+k+1)*x - 1; down = max((now/x+k)*x,a[i]); } // cout << "[" << down << "," << up << "]" << endl; LL rindex = min((LL)(upper_bound(a+i,a+n,up) - a),n-1); if (a[rindex] > up) rindex --; LL lindex = lower_bound(a,a+n,down) - a; // get [lindex,rindex] res += rindex - lindex + 1; // cout << lindex << " " << rindex << " "; // cout << res << endl; } cout << res; return 0; }