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
4 2 0 5 3 1 7
4
5 3 1 3 3 3 3 3
25
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.
题意:给定n个数,从这些数中找到一个序列(i,j),使得[a[i],a[j]]中恰好有k个数是x的倍数,求一共有多少个序列(PS:对于序列来说i,j的关系是无序的,也就是说可以i<j || i >= j)
思路: 基于lower_bound函数
先排序 然后可以把各个点放在数轴上 从a[i]开始找出第一个大于等于a[i]的x的倍数p的位置 再找出p+k*x的位置q 这两个位置之间包含了k+1个能被x整除的数 然后找出p+(k-1)*x的位置m p的位置到m就是满足的区间 所以q-m就是以a[i]为前区间到 q位置满足题意区间的个数
max(a[i],p+(k-1)*x)是k=0时的情况
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define LL long long
using namespace std;
int n;
LL x,k,a[100010];
int main()
{
scanf("%d %I64d %I64d",&n,&x,&k);
for(int i = 0; i < n; i++)
scanf("%ld",&a[i]);
sort(a,a+n);
LL sum = 0;
for(int i = 0; i < n; i++)
{
LL p = ceil(a[i]*1.0/x)*x;
sum += lower_bound(a,a+n,p+k*x)-lower_bound(a,a+n,max(a[i],p+(k-1)*x));
}
printf("%I64d\n",sum);
return 0;
}
头文件<math>
ceil()函数 向正无穷取整 ceil(1.1) = 2
floor()函数 向负无穷去整 floor(-1.4) = -2 floor(1.4) = 1
fix()函数 向0取整 fix(-1.3) = -1 fix(1.4) = 1
round()函数 四舍五入最近整数 round(-1.3) = -1 roung(-1.52) = -2 round(1.3) = 1 round(1.52) = 2
头文件<algorithm>
upper_bound(point, point + 5, 7)
按从小到大,7最多能插入数组point的哪个位置
lower_bound(point, point + 5, 7)
按从小到大,7最少能插入数组point的哪个位置
#include <iostream>
#include <algorithm>//必须包含的头文件
using namespace std;
int main(){
}
output:
4
2