This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int MAXN=1e5;
int n;
int l[MAXN], r[MAXN];
vector<int> adj[MAXN];
int in[MAXN], out[MAXN], level[MAXN];
int timer=0;
bool compare(int x, int y)
{
if (r[x]==r[y])
return l[x]<l[y];
return r[x]<r[y];
}
void traverse(int x, int k)
{
level[x]=k;
timer=timer+1;
in[x]=timer;
for (auto y : adj[x])
traverse(y, k+1);
out[x]=timer;
return;
}
bool ancestor(int x, int y)
{
return in[x]>=in[y] && out[x]<=out[y];
}
int main()
{
int q;
cin >> n >> q;
for (int i=0; i<n; i++)
cin >> l[i] >> r[i];
int sorted[n];
for (int i=0; i<n; i++)
sorted[i]=i;
sort(sorted, sorted+n, compare);
int parent[n];
for (int i=0; i<n; i++)
parent[i]=-1;
int leftmost=sorted[n-1];
for (int i=n-1; i>=0; i--)
{
int x=sorted[i];
if (l[leftmost]<=r[x] && leftmost!=x)
{
parent[x]=leftmost;
adj[leftmost].push_back(x);
}
if (l[x]<l[leftmost])
leftmost=x;
}
for (int i=0; i<n; i++)
if (parent[i]==-1)
traverse(i, 0);
while (q--)
{
int x, y;
cin >> x >> y;
x=x-1;
y=y-1;
if (x==y)
{
cout << 0 << '\n';
continue;
}
if (r[x]==r[y])
{
cout << 1 << '\n';
continue;
}
if (ancestor(x, y))
cout << level[x]-level[y] << '\n';
else
cout << "impossible" << '\n';
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |