B. XK Segments (二分)

  • 题意:给你三个整数,n,x,k。再给你一个大小为 n 的数组a,要你找出不同的下标对 (i,j) 的对数,是其满足:a[i]<=a[j] 且 在 [ a[i] , a[j] ] 内,恰好有k个能被x整除的数。
  • 算法:二分
  • 思路:先sort一下,因为要求的只是下标对数所以sort不影响。1~n 遍历a[i], 对于每一个a[i], 从 a[j]>=a[i] 的范围里,计算得到 最小满足条件的值l 和 最大满足条件的值r (令在>=a[i] 的范围内的第一个能整除x的数为 fir=a[i]/x + (a[i]%x!=0) , 则 l=(fir+k-1)*x, r=l+x ), 使得 所有在 [l, r) 中的 a[j] 都能满足条件。然后 ans = lower_bound(r) - lower_bound(l)

#include <bits/stdc++.h>
#define pi acos(-1)
#define fastcin ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(0);
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const LL LL_INF = 1LL<<62;
const int maxn = 100000 + 10;
const int mod = 1e9 + 7;

int a[maxn];

int main()
{
    int n, x, k;
    scanf("%d%d%d", &n, &x, &k);
    for(int i=0; i<n; i++) scanf("%d", &a[i]);
    sort(a, a+n);
    LL ans=0;
    for(int i=0; i<n; i++){
        LL fir = a[i]/x + (a[i]%x!=0);
        LL l = (fir + k-1)*x;
        LL r = l+x;
        if(k==0){
            l = a[i];
            r = fir*x;
        }
        ans += lower_bound(a, a+n, r) - lower_bound(a, a+n, l);
    }
    printf("%I64d\n", ans);
}

猜你喜欢

转载自blog.csdn.net/qq_37352710/article/details/80533259