[codility]Number-of-disc-intersections

// you can also use includes, for example:
#include <algorithm>
struct IntervalSeg
{
    long long left, right;
    IntervalSeg(long long _left = 0, long long _right = 0):left(_left),right(_right){}
    bool operator<(const IntervalSeg& orh) const
    {
        if(left == orh.left) return right < orh.right;
        else return left < orh.left;
    }
};

int getFirstBiggerIdx(const vector<IntervalSeg>& intervalSeg, long long target)
{
    int left = 0;
    int right = intervalSeg.size()-1;
    while(left <= right)
    {
        int mid = left+(right-left)/2;
        if(intervalSeg[mid].left > target) right = mid-1;
        else left = mid+1;
    }
    return left;
}
int solution(const vector<int> &A) {
    // write your code in C++98
    //...convert original problem to counting overlap number of given interval segments
    vector<IntervalSeg> intervalSeg(A.size());
    for(int i = 0; i < A.size(); ++i)
    {
        intervalSeg[i].left = intervalSeg[i].right = i;
        intervalSeg[i].left -= A[i];
        intervalSeg[i].right += A[i];
    }
    //...first interval segments first
    sort(intervalSeg.begin(), intervalSeg.end());
    //...enumerate each interval segment and using binary search to calculate how much interval segments overlap it
    long long result = 0;
    for(int i = 0; i < intervalSeg.size(); ++i)
    {
        long long curRight = intervalSeg[i].right;
        int firstBiggerIdx = getFirstBiggerIdx(intervalSeg, curRight);
        result += firstBiggerIdx-i-1;
    }
    //...return result
    long long MAX_LIMIT = 10000000;
    if(result > MAX_LIMIT) return -1;
    else return (int)result;
}

你可能感兴趣的:([codility]Number-of-disc-intersections)