Algorithm 使用二进制搜索将间隔插入不相交的间隔集中

Algorithm 使用二进制搜索将间隔插入不相交的间隔集中,algorithm,Algorithm,给定 任务是将一个区间插入不相交的区间集或区间列表。比如说 class Interval{ int start; int end; } into-gives 给予 等等。 我知道我们应该使用2个二进制搜索来寻找最有效的解决方案,并且我们应该比较插入间隔的开始和列表间隔的结束,反之亦然。当我们无法准确地找到我们要查找的内容时,如何准确地处理二进制搜索?计算节点数。返回中心,如果适用,插入。否则,决定列表中哪一半是感兴趣的。回到它的中心,插入等。你需要处理异常到.< /p> 假设C+

给定

任务是将一个区间插入不相交的区间集或区间列表。比如说

class Interval{
   int start;
   int end;
}
into-gives
给予
等等。

我知道我们应该使用2个二进制搜索来寻找最有效的解决方案,并且我们应该比较插入间隔的开始和列表间隔的结束,反之亦然。当我们无法准确地找到我们要查找的内容时,如何准确地处理二进制搜索?

计算节点数。返回中心,如果适用,插入。否则,决定列表中哪一半是感兴趣的。回到它的中心,插入等。你需要处理异常到.< /p>

假设C++,我会使用一个<代码> STD::MAP<代码>从区间结束到间隔开始。 要进行搜索,请使用

std::upper_bound()
查找第一个重叠项 间隔,然后推进迭代器以查找所有重叠的间隔。 只需要一次二进制搜索

<4,8> into <3,7><10,13><20,21><30,31><40,45> gives <3,8><10,13><20,21><30,31><40,45>

<1,30> into <3,7><10,13><20,21><30,31><40,45> gives <1,30><40,45>

and etc.
#包括
#包括
typedef std::map IntervalMap;
结构间隔{
int启动;
内端;
};
int main()
{
间隔图;
区间查询;
imap[7]=3;//
imap[13]=10;//
//插入:
query.start=4;
query.end=8;
//找到第一个重叠区间
auto it=imap.upper_-bound(query.start);
if(it!=imap.end()&&it->secondsecondsecond;
while(it!=imap.end()&&it->secondfirst>query.end)
query.end=it->first;
自动tmp=it;
++它;
imap.erase(tmp);
}
}
//插入新的间隔
imap[query.end]=query.start;
for(auto-it=imap.begin();it!=imap.end();++it)
{
fprintf(stderr,“\n”,it->second,it->first);
}
返回0;
}
#include <map>
#include <stdio.h>

typedef std::map<int, int> IntervalMap;

struct Interval {
    int start;
    int end;
};

int main()
{
    IntervalMap imap;
    Interval query;

    imap[7] = 3;    // <3,7>
    imap[13] = 10;  // <10,13>

    // Insert: <4,8>
    query.start = 4;
    query.end = 8;

    // Find the first overlapping interval
    auto it = imap.upper_bound(query.start);
    if (it != imap.end() && it->second < query.end)
    {
        // There is one or more overlapping interval
        // Update lower bound for the new interval
        if (it->second < query.start)
            query.start = it->second;

        while (it != imap.end() && it->second < query.end)
        {
            // Update upper bound for the new interval
            if (it->first > query.end)
                query.end = it->first;

            auto tmp = it;
            ++it;
            imap.erase(tmp);
        }
    }

    // Insert the new interval
    imap[query.end] = query.start;

    for (auto it = imap.begin(); it != imap.end(); ++it)
    {
        fprintf(stderr, "<%d,%d>\n", it->second, it->first);
    }

    return 0;
}