제출 #1173162

#제출 시각아이디문제언어결과실행 시간메모리
1173162domblyEvent Hopping (BOI22_events)C++20
20 / 100
105 ms25280 KiB
#include <bits/stdc++.h>
#define F first
#define S second

using namespace std;

const int N = 1e5 + 10;

const int LOG = 17;

int n, l[N], r[N], up[N][LOG], logs[N];
pair<int,int> st[N][LOG];

bool cmp(int i, int j) {
  if(r[i] == r[j]) return l[i] < l[j];
  return r[i] < r[j];
}

pair<int,int> Query(int l, int r) {
  int j = logs[r - l + 1];
  return min(st[l][j], st[r - (1 << j) + 1][j]);
}

signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  int q;
  cin >> n >> q;
  for(int i = 2; i <= n; i++) logs[i] = logs[i >> 1] + 1;
  vector<int> xs;
  for(int i = 1; i <= n; i++) {
    cin >> l[i] >> r[i];
    xs.push_back(l[i]);
    xs.push_back(r[i]);
  }
  sort(xs.begin(), xs.end());
  xs.erase(unique(xs.begin(), xs.end()), xs.end());
  for(int i = 1; i <= n; i++) {
    l[i] = lower_bound(xs.begin(), xs.end(), l[i]) - xs.begin() + 1;
    r[i] = lower_bound(xs.begin(), xs.end(), r[i]) - xs.begin() + 1;
  }
  vector<int> order(n + 1), p(n + 1);
  for(int i = 1; i <= n; i++) order[i] = i;
  sort(order.begin() + 1, order.end(), cmp);
  for(int i = 1; i <= n; i++) p[order[i]] = i;
  //for(int i = 1; i <= n; i++) cout << l[order[i]] << " " << r[order[i]] << endl;
  vector<int> L(n + 1), R(n + 1);
  for(int i = 1; i <= n; i++) {
    L[i] = l[order[i]];
    R[i] = r[order[i]];
  }
  for(int i = 1; i <= n; i++) st[i][0] = {L[i], i};
  for(int j = 1; j < LOG; j++) {
    for(int i = 1; i + (1 << (j - 1)) <= n; i++) {
      st[i][j] = min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
    }
  }
  vector<int> prv(n + 1);
  for(int i = 1; i <= n; i++) {
    int tl = 1, tr = i, rez = i;
    while(tl <= tr) {
      int mid = tl + tr >> 1;
      if(R[mid] >= L[i]) {
        rez = mid;
        tr = mid - 1;
      } else {
        tl = mid + 1;
      }
    }
    prv[i] = rez;
    up[i][0] = Query(rez, i).S;
  }
  for(int j = 1; j < LOG; j++) {
    for(int i = 1; i <= n; i++) {
      up[i][j] = up[up[i][j - 1]][j - 1];
    }
  }
  while(q--) {
    int x, y;
    cin >> x >> y;
    x = p[x]; y = p[y];
    if(x == y) {
      cout << "0\n";
      continue;
    }
    if (L[y] <= R[x] && R[x] <= R[y]) {
      cout << "1\n";
      continue;
    }
    if(x > y) {
      cout << "impossible\n";
      continue;
    }
    int res = 1;
    for(int j = LOG - 1; j >= 0; j--) {
      if(up[y][j] > x) {
        res += (1 << j);
        y = up[y][j];
      }
    }
    if(up[y][0] > x) {
      cout << "impossible\n";
    } else {
      cout << res << "\n";
    }
  }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...