📜  最大不相交间隔

📅  最后修改于: 2021-05-06 09:11:10             🧑  作者: Mango

给定一组N个间隔,任务是找到相互不相交的间隔的最大集合。如果两个间隔[i,j][k,l]没有共同点,则称它们是不相交的。
例子:

方法:

  1. 根据它们的终点对时间间隔进行排序。
  2. 现在,遍历所有间隔,如果我们得到两个重叠的间隔,则贪婪地选择具有较低端点的间隔,因为选择该间隔将确保进一步容纳间隔而不会出现任何重叠。
  3. 对所有间隔应用相同的步骤,并打印满足上述条件的所有间隔。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
#define ll long long int
 
// Function to sort the vector elements
// by second element of pairs
bool sortbysec(const pair& a,
               const pair& b)
{
    return (a.second < b.second);
}
 
// Function to find maximal disjoint set
void maxDisjointIntervals(vector > list)
{
 
    // Sort the list of intervals
    sort(list.begin(), list.end(), sortbysec);
 
    // First Interval will always be
    // included in set
    cout << "[" << list[0].first << ", "
         << list[0].second << "]" << endl;
 
    // End point of first interval
    int r1 = list[0].second;
 
    for (int i = 1; i < list.size(); i++) {
        int l1 = list[i].first;
        int r2 = list[i].second;
 
        // Check if given interval overlap with
        // previously included interval, if not
        // then include this interval and update
        // the end point of last added interval
        if (l1 > r1) {
            cout << "[" << l1 << ", "
                 << r2 << "]" << endl;
            r1 = r2;
        }
    }
}
 
// Driver code
int main()
{
    int N = 4;
    vector > intervals = { { 1, 4 },
                                          { 2, 3 },
                                          { 4, 6 },
                                          { 8, 9 } };
    maxDisjointIntervals(intervals);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
class GFG
{
    static class Pair implements Comparable
    {
        int first, second;
          
        Pair(int f, int s)
        {
            first = f;
            second = s;
        }
  
        @Override
       
     // Function to sort the vector elements
     // by second element of Pairs
        public int compareTo(Pair o)
        {
            if(this.second > o.second)
                return 1;
            else if(this.second == o.second)
                return 0;
            return -1;
        }
    }
 
// Function to find maximal disjoint set
static void maxDisjointIntervals(Pair []list)
{
 
    // Sort the list of intervals
    Collections.sort(Arrays.asList(list));
 
    // First Interval will always be
    // included in set
    System.out.print("[" +  list[0].first+ ", "
         + list[0].second+ "]" +"\n");
 
    // End point of first interval
    int r1 = list[0].second;
 
    for (int i = 1; i < list.length; i++) {
        int l1 = list[i].first;
        int r2 = list[i].second;
 
        // Check if given interval overlap with
        // previously included interval, if not
        // then include this interval and update
        // the end point of last added interval
        if (l1 > r1) {
            System.out.print("[" +  l1+ ", "
                 + r2+ "]" +"\n");
            r1 = r2;
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    int N = 4;
    Pair []intervals = { new Pair(1, 4 ),
            new Pair( 2, 3 ),
            new Pair( 4, 6 ),
            new Pair( 8, 9 ) };
    maxDisjointIntervals(intervals);
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 implementation of the approach
 
# Function to find maximal disjoint set
def maxDisjointIntervals(list_):
     
    # Lambda function to sort the list 
    # elements by second element of pairs
    list_.sort(key = lambda x: x[1])
     
    # First interval will always be
    # included in set
    print("[", list_[0][0], ", ", list_[0][1], "]")
     
    # End point of first interval
    r1 = list_[0][1]
     
    for i in range(1, len(list_)):
        l1 = list_[i][0]
        r2 = list_[i][1]
         
        # Check if given interval overlap with
        # previously included interval, if not
        # then include this interval and update
        # the end point of last added interval
        if l1 > r1:
            print("[", l1, ", ", r2, "]")
            r1 = r2
             
 
# Driver code
if __name__ == "__main__":
     
    N = 4
    intervals = [ [ 1, 4 ], [ 2, 3 ],
                  [ 4, 6 ], [ 8, 9 ] ]
     
    # Call the function
    maxDisjointIntervals(intervals)
 
# This code is contributed by Tokir Manva


输出:
[2, 3]
[4, 6]
[8, 9]