c_cpp 给出大量间隔[ai,bi],找到与最多间隔相交的点

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 给出大量间隔[ai,bi],找到与最多间隔相交的点相关的知识,希望对你有一定的参考价值。

My python version: https://gist.github.com/sundeepblue/681596a219c85af92d24abed1f97ffb2

给你一个超长list。list每个element是一个数组。例如:[[1, 5], [10, 16], [2, 7], ...........[1000, 1027]]
数组第一个数表示司机启动车时间,第二个数是送乘客到达时间。问,从这个输入数组来给出在线司机最多的起止时间。比如答案可以是[16, 801]




/*
http://csjobinterview.wordpress.com/2012/04/02/the-section-which-intersects-with-the-largest-number-of-intervals/

http://haixiaoyang.wordpress.com/2012/03/19/find-the-point-intersect-with-most-intervals/

store each boundary value as a separate element in an array with the information whether it's the start boundary or end boundary. 
Sort this array by boundary value. 
initialize an integer overLapCount = 0; 
Traverse this array from start to finish 
whenever you cross a "Start" boundary, increment overlapCount 
whenever you cross an "End" boundary, decrement overlapCount 
store the maxOverLapCountSoFar 
at the end of the traversal you will have the information about what is the maximum possible overlap for a range. 
You can easily modify this to store the range information as well.

Example 1: by given [1,5] [2,4],[3,6], [7,8], [8,10], it should return an interval [3,4].
 
Example 2: However, if some of the starting/ending points are mixed, for example [1,3], [2,3], [3,4],[3,5], then the point 3 intersect with the most number of intervals and should be therefore returned.


*/


struct interval {
    int begin;
    int end;
};

struct point {
    int value;
    bool is_begin;
    point(int v, bool b) : value(v), is_begin(b) {}
    //bool operator < (const point & p) { return value < p.value; }
};

int find_point (vector<interval> &vi) {
    vector<point> vp;
    for(auto i : vi) {
        vp.push_back(point(i.begin, true));
        vp.push_back(point(i.end, false));
    }
    sort(vp.begin(), vp.end(), [] (const point &p1, const point &p2) { return p1.value < p2.value; } );
    
    int curr_intersect = 0;
    int max_intersect = 0;
    int final_begin = 0;
    int res = 0;
    
    for(point p : vp) {
        if(p.is_begin) {
            curr_intersect++;
            if(max_intersect < curr_intersect) {
                max_intersect = curr_intersect;
                final_begin = p.value;
            }
        }
        else {
            // why??? not understand!
            if(curr_intersect == max_intersect)  // gist to pass Example 2
                res = (p.value + final_begin)/2;
            curr_intersect--;
        }
    }
    return res;
}

int main() {
    vector<interval> vi = {{1,3}, {2,3}, {3,4}, {3,5}};
    cout << find_point(vi);
}

以上是关于c_cpp 给出大量间隔[ai,bi],找到与最多间隔相交的点的主要内容,如果未能解决你的问题,请参考以下文章

贪心算法——间隔任务规划——python

2021-5-12 C - Maximal Value

LA3905

邻项交换排序

BZOJ2590: [Usaco2012 Feb]Cow Coupons

c_cpp 找到大量数字中最大的k数。您无法对数组进行排序。