zoukankan      html  css  js  c++  java
  • Codeforces 895B. XK Segments

    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).

    Input

    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.

    Output

    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;   
    }  
    View Code
  • 相关阅读:
    springboot配置大全
    springboot上传文件时500错误,提示临时目录无效
    Springboot上传文件临时目录无效
    SpringBoot 文件上传临时文件路径问题
    SpringBoot 上传文件到linux服务器 异常java.io.FileNotFoundException: /tmp/tomcat.50898……解决方案
    tomcat下的work目录和temp目录
    Http协议报文格式
    multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
    Nginx的三种应用场景介绍
    SpringBoot: 浅谈文件上传和访问的坑 (MultiPartFile)
  • 原文地址:https://www.cnblogs.com/ToTOrz/p/7905844.html
Copyright © 2011-2022 走看看