This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("O3","unroll-loops","Ofast")
#pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
namespace{
const int INF=1e9;
#define pii pair<int,int>
#define endl '\n'
vector<pii> tmp;
inline pii comb(pii a,pii b){
return {min(a.first,b.first),max(a.second,b.second)};
}
struct seg{
int l,m,r;
int maxval=-INF,minval=INF;
int maxlz=-INF,minlz=INF;
seg *lc,*rc;
int rmax(){
return max(maxlz,maxval);
}
int rmin(){
return min(minlz,minval);
}
void pull(){
maxval=max(lc->rmax(),rc->rmax());
minval=min(lc->rmin(),rc->rmin());
}
void push(){
lc->maxlz=max(lc->maxlz,maxlz);
rc->maxlz=max(rc->maxlz,maxlz);
lc->minlz=min(lc->minlz,minlz);
rc->minlz=min(rc->minlz,minlz);
}
seg(int l1,int r1){
l=l1,r=r1;
m=(l+r)>>1;
if(r-l==1){
maxval=minval=maxlz=minlz=l1;
return;
}
lc=new seg(l,m);
rc=new seg(m,r);
pull();
}
void add(int a,int b,int x){
if(a<=l&&b>=r){
maxlz=max(maxlz,x);
minlz=min(minlz,x);
return;
}
push();
if(a<m){
lc->add(a,b,x);
}
if(b>m){
rc->add(a,b,x);
}
pull();
}
pii ask(int a,int b){
if(a<=l&&b>=r){
return {rmin(),rmax()};
}
pii ans={INF,-INF};
push();
if(a<m){
ans=comb(ans,lc->ask(a,b));
}
if(b>m){
ans=comb(ans,rc->ask(a,b));
}
pull();
return ans;
}
};
int main1(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int n,k;cin>>n>>k;
vector<seg*> v(18);
for(int i=0;i<18;i++){
v[i]=new seg(0,n);
}
vector<vector<pii>> dp(18,vector<pii>(n));
int m;cin>>m;
for(int i=0;i<m;i++){
int a,b;cin>>a>>b;a--;b--;
if(a<b){
int c=min(a+k,b);
v[0]->add(a,c,b);
}
else{
int c=max(b+1,a-k+1);
v[0]->add(c,a+1,b);
}
}
for(int j=0;j<n;j++){
dp[0][j]=v[0]->ask(j,j+1);
}
for(int i=1;i<18;i++){
for(int j=0;j<n;j++){
v[i]->add(j,j+1,dp[i-1][j].first);
v[i]->add(j,j+1,dp[i-1][j].second);
}
for(int j=0;j<n;j++){
int a,b;tie(a,b)=dp[i-1][j];
dp[i][j]=v[i]->ask(a,b+1);
}
}
int q;cin>>q;
for(int i=0;i<q;i++){
int a,b;cin>>a>>b;a--;b--;
if(a<b){
int ans=0;
int l=a,r=a;
bool flag=0;
for(int j=17;j>=0;j--){
int c,d;
tie(c,d)=v[j]->ask(l,r+1);
if(d<b){
ans+=(1<<(j-1));
l=c,r=d;
}
else{
flag=1;
}
}
if(flag==0){
cout<<-1<<endl;
}
else{
cout<<ans+1<<endl;
}
}
else{
int ans=0;
int l=a,r=a;
bool flag=0;
for(int j=17;j>=0;j--){
int c,d;
tie(c,d)=v[j]->ask(l,r+1);
if(c>b){
ans+=(1<<(j-1));
l=c,r=d;
}
else{
flag=1;
}
}
if(flag==0){
cout<<-1<<endl;
}
else{
cout<<ans+1<<endl;
}
}
}
return 0;
}
}
int32_t main(){
main1();
}
# | 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... |