📌  相关文章
📜  检查在任何点上是否有任何K范围重叠

📅  最后修改于: 2021-05-06 23:16:47             🧑  作者: Mango

给定N个范围[L,R]和整数K ,任务是检查是否有K个范围在任何点重叠。

例子:

方法:想法是制作一个向量对,并将每个范围的起点成对存储在该向量中,将其作为(起点-1),将终点作为(终点1)。现在,对向量进行排序,然后遍历向量,如果当前元素是起点,则将其推入堆栈中;如果当前元素是终点,则从堆栈中弹出一个元素。如果在任何时间实例中,堆栈的大小都大于或等于K,则打印“是”,否则最后打印“”。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Comparator to sort the vector of pairs
bool sortby(const pair& a,
            const pair& b)
{
    if (a.first != b.first)
        return a.first < b.first;
    return (a.second < b.second);
}
 
// Function that returns true if any k
// segments overlap at any point
bool kOverlap(vector > pairs, int k)
{
    // Vector to store the starting point
    // and the ending point
    vector > vec;
    for (int i = 0; i < pairs.size(); i++) {
 
        // Starting points are marked by -1
        // and ending points by +1
        vec.push_back({ pairs[i].first, -1 });
        vec.push_back({ pairs[i].second, +1 });
    }
 
    // Sort the vector by first element
    sort(vec.begin(), vec.end());
 
    // Stack to store the overlaps
    stack > st;
 
    for (int i = 0; i < vec.size(); i++) {
        // Get the current element
        pair cur = vec[i];
 
        // If it is the starting point
        if (cur.second == -1) {
            // Push it in the stack
            st.push(cur);
        }
 
        // It is the ending point
        else {
            // Pop an element from stack
            st.pop();
        }
 
        // If more than k ranges overlap
        if (st.size() >= k) {
            return true;
        }
    }
 
    return false;
}
 
// Driver code
int main()
{
    vector > pairs;
    pairs.push_back(make_pair(1, 3));
    pairs.push_back(make_pair(2, 4));
    pairs.push_back(make_pair(3, 5));
    pairs.push_back(make_pair(7, 10));
 
    int n = pairs.size(), k = 3;
 
    if (kOverlap(pairs, k))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Stack;
 
class GFG{
 
static class Pair
{
    int first, second;
 
    public Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function that returns true if any k
// segments overlap at any point
static boolean kOverlap(ArrayList pairs,
                        int k)
{
     
    // Vector to store the starting point
    // and the ending point
    ArrayList vec = new ArrayList<>();
    for(int i = 0; i < pairs.size(); i++)
    {
         
        // Starting points are marked by -1
        // and ending points by +1
        vec.add(new Pair(pairs.get(i).first, -1));
        vec.add(new Pair(pairs.get(i).second, +1));
    }
     
    // Sort the vector by first element
    Collections.sort(vec, new Comparator()
    {
         
        // Comparator to sort the vector of pairs
        public int compare(Pair a, Pair b)
        {
            if (a.first != b.first)
                return a.first - b.first;
                 
            return (a.second - b.second);
        }
    });
 
    // Stack to store the overlaps
    Stack st = new Stack<>();
 
    for(int i = 0; i < vec.size(); i++)
    {
         
        // Get the current element
        Pair cur = vec.get(i);
 
        // If it is the starting point
        if (cur.second == -1)
        {
             
            // Push it in the stack
            st.push(cur);
        }
 
        // It is the ending point
        else
        {
             
            // Pop an element from stack
            st.pop();
        }
 
        // If more than k ranges overlap
        if (st.size() >= k)
        {
            return true;
        }
    }
    return false;
}
 
// Driver code
public static void main(String[] args)
{
    ArrayList pairs = new ArrayList<>();
    pairs.add(new Pair(1, 3));
    pairs.add(new Pair(2, 4));
    pairs.add(new Pair(3, 5));
    pairs.add(new Pair(7, 10));
 
    int n = pairs.size(), k = 3;
 
    if (kOverlap(pairs, k))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by sanjeev2552


Python3
# Python3 implementation of the approach
 
# Function that returns true if any k
# segments overlap at any point
def kOverlap(pairs: list, k):
 
    # Vector to store the starting point
    # and the ending point
    vec = list()
    for i in range(len(pairs)):
 
        # Starting points are marked by -1
        # and ending points by +1
        vec.append((pairs[0], -1))
        vec.append((pairs[1], 1))
 
    # Sort the vector by first element
    vec.sort(key = lambda a: a[0])
 
    # Stack to store the overlaps
    st = list()
 
    for i in range(len(vec)):
 
        # Get the current element
        cur = vec[i]
 
        # If it is the starting point
        if cur[1] == -1:
 
            # Push it in the stack
            st.append(cur)
 
        # It is the ending point
        else:
 
            # Pop an element from stack
            st.pop()
 
        # If more than k ranges overlap
        if len(st) >= k:
            return True
    return False
 
 
# Driver Code
if __name__ == "__main__":
    pairs = list()
    pairs.append((1, 3))
    pairs.append((2, 4))
    pairs.append((3, 5))
    pairs.append((7, 10))
 
    n = len(pairs)
    k = 3
 
    if kOverlap(pairs, k):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# sanjeev2552


C#
// C# implementation of the approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
 
// Function that returns true if any k
// segments overlap at any point
static bool kOverlap(List> pairs,
                        int k)
{
     
    // Vector to store the starting point
    // and the ending point
    List> vec = new List>();
    for(int i = 0; i < pairs.Count; i++)
    {
         
        // Starting points are marked by -1
        // and ending points by +1
        vec.Add(new Tuple(pairs[i].Item1,-1));
        vec.Add(new Tuple(pairs[i].Item2,1));
    }
    vec.Sort();
 
    // Stack to store the overlaps
    Stack st = new Stack();
    for(int i = 0; i < vec.Count; i++)
    {
         
        // Get the current element
        Tuple cur = vec[i];
 
        // If it is the starting point
        if (cur.Item2 == -1)
        {
             
            // Push it in the stack
            st.Push(cur);
        }
 
        // It is the ending point
        else
        {
             
            // Pop an element from stack
            st.Pop();
        }
 
        // If more than k ranges overlap
        if (st.Count >= k)
        {
            return true;
        }
    }
    return false;
}
 
// Driver code
public static void Main(params string[] args)
{
    List> pairs = new List>();
    pairs.Add(new Tuple(1, 3));
    pairs.Add(new Tuple(2, 4));
    pairs.Add(new Tuple(3, 5));
    pairs.Add(new Tuple(7, 10));
 
    int n = pairs.Count, k = 3;
    if (kOverlap(pairs, k))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by rutvik_56/


输出:
Yes