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;
#define sz(x) (int)(x).size()
#define all(x) begin(x), end(x)
#define forn(i,a,b) for(int i=(a);i<(b);i++)
#define fore(i,a,b) for(int i=(a);i<=(b);i++)
#define pb push_back
#define F first
#define S second
using ll = long long;
using ii = pair<ll, ll>;
static constexpr int INF = 1e9;
int n,K,Q;
vector<int> a, lnxt, rnxt;
vector<vector<int>> adj;
vector<int> getLeft()
{
vector<int> res(n, -1);
vector<int> s;
forn(i,0,n)
{
while (!s.empty() && a[s.back()] < a[i]) s.pop_back();
if (!s.empty())
{
res[i] = s.back();
if (a[s.back()] == a[i]) s.pop_back();
}
s.pb(i);
}
return res;
}
int bfs(int s, int t)
{
vector<int> dist(n, INF);
queue<int> q;
dist[s] = 0;
q.push(s);
while (!q.empty())
{
int u = q.front(); q.pop();
for (const auto v : adj[u])
{
if (dist[v] < INF) continue;
dist[v] = dist[u] + 1;
q.push(v);
}
}
assert(dist[t] != INF);
return dist[t];
}
void connect(int u, int v)
{
adj[u].pb(v);
adj[v].pb(u);
}
int main()
{
cin.tie(0)->sync_with_stdio(0);
cin>>n>>K>>Q;
a.resize(n); adj.resize(n);
forn(i,0,n)
{
cin>>a[i];
a[i]--;
}
lnxt = getLeft();
reverse(all(a));
rnxt = getLeft();
reverse(all(rnxt));
reverse(all(a));
forn(i,0,n)
{
if (rnxt[i] != -1) rnxt[i] = n - 1 - rnxt[i];
}
forn(i,0,n)
{
if (lnxt[i] != -1) connect(i, lnxt[i]);
if (rnxt[i] != -1) connect(i, rnxt[i]);
}
forn(z,0,Q)
{
int u,v; cin>>u>>v; u--; v--;
cout << bfs(u, v) - 1 << '\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... |