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
  • 相关阅读:
    IO流之File类
    CPU单核多核区别【转载】
    [转载] MySQL的四种事务隔离级别
    事务的四大特性,以及隔离级别
    [转载] spring aop 环绕通知around和其他通知的区别
    [转载] Spring框架——AOP前置、后置、环绕、异常通知
    spring框架 AOP核心详解
    汇编语言--操作数的寻址方式(三)
    汇编语言--CPU资源和存储器(二)
    汇编语言学习--基础知识(一)
  • 原文地址:https://www.cnblogs.com/ToTOrz/p/7905844.html
Copyright © 2011-2022 走看看