这是您可以遵循的方法。假设给你
范围为 [1 到 N],其中 N 可以是可变的(来自用户的输入)/常数(已经固定)。
子集为 Ai[ai, bi],其中 1<=i<=k。即您有 k 个子集,其中 ai 是下边界,bi 是上边界。
现在开始创建第一个节点为 [1,N] 的树。在算法执行期间的给定时间,在树中,每个叶节点表示没有被任何给定子集覆盖的数字范围,即您必须打印所有叶节点的数字范围。
初始条件
一开始,Tree 只有一个叶节点 [1,N]。即因为我们还没有处理任何子集,所以我们必须打印 1 到 N 之间的所有数字。
终止条件
在算法树的末尾将包含许多叶子。每个叶子将代表未被任何子集覆盖的数字范围。所以你必须打印这些数字作为输出。
算法:
STEP 1: Creating the Tree
For i = 1 to k //process for all given subsets
{
For every leaf node in current tree
{
//Let [x,y] is the current leaf node being processed
1. if(ai>=x && bi<=y) //subset being processed lie inside the leaf being
processed.
create nodes [x,ai-x] and [bi+1,y] and attach as child of the leaf node
being processed.
2. if((x<=ai<y) && (bi>y)) //subset overflows towards right
create a node [x, ai-1] and attach as child to the current leaf node being
processed.
3. if((ai<x) && (x<bi<=y)) //subset overflows towards left
create a node [bi+1, y] and attach as child to the current leaf node being
processed.
}
}
STEP 2: Printing the output
//Now the leaf nodes indicate the numbers to be printed.
For each leaf node [x,y] of the resulting tree
{
//you will get some leaf node with x>y
if(x<=y)
print the numbers in range [x,y].
}