suarez hacker earth

mail@pastecode.io avatar
unknown
java
6 months ago
1.5 kB
5
Indexable
Never
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    int N = scanner.nextInt();
    Segment[] segments = new Segment[N];
    long max = Long.MIN_VALUE;
    long min = Long.MAX_VALUE;

    for (int i = 0; i < N; i++) {
      long start = scanner.nextLong();
      long end = scanner.nextLong();
      
      if(min > start){
        min = start;
      }
      if(max < end){
        max = end;
      }
      
      segments[i] = new Segment(start, end);
      
    }

    Arrays.sort(segments, new RangeSort());
    
    long Q = scanner.nextLong();
    for (long i = 0; i < Q; i++) {
      long K = scanner.nextLong();
      long X = scanner.nextLong();

      long count = 0;
      long result = -1;
      
      if((X > max) || (X < min)){
        System.out.println(-1);
        continue;
      }

      for (Segment segment : segments) {
        if (segment.start <= X && X <= segment.end) {
          count++;
          if (count == K) {
            result = segment.end - segment.start + 1;
            break;
          }
        }
      }

      System.out.println(result);
    }
  }
}

class Segment {
  long start;
  long end;

  public Segment(long start, long end) {
    this.start = start;
    this.end = end;
  }
}

class RangeSort implements Comparator<Segment> {
  public int compare(Segment a, Segment b){
    return (int)((a.end - a.start) - (b.end - b.start));
  }
}
 
Leave a Comment