• 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
  • 相关阅读:
    tensorflow笔记(四)之MNIST手写识别系列一
    tensorflow笔记(三)之 tensorboard的使用
    tensorflow笔记(二)之构造一个简单的神经网络
    tensorflow笔记(一)之基础知识
    Andrew Ng机器学习课程笔记(六)之 机器学习系统的设计
    Andrew Ng机器学习课程笔记(五)之应用机器学习的建议
    POJ题目分类
    codeforces 355A Vasya and Digital Root
    ubuntu清理系统垃圾与备份
    poj 1742 Coins (多重背包)
  • 原文地址:https://www.cnblogs.com/ToTOrz/p/7905844.html
Copyright © 2020-2023  润新知