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("Ofast","unroll-all-loops")
#include <bits/stdc++.h>
using namespace std;
// #define int long long
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int H,W,Q;
cin >> H >> W >> Q;
vector<int> A(H+1);
vector liftmaxH(H+1,vector(16,0ll));
for(int i=1;i<=H;i++) {
cin>>A[i];
liftmaxH[i][0]=A[i];
}
for(int bit=1;bit<16;bit++) {
for(int i=1;i<=H;i++) {
if(i+(1<<bit)-1>H)continue;
liftmaxH[i][bit]=max(liftmaxH[i][bit-1],liftmaxH[i+(1<<(bit-1))][bit-1]);
}
}
vector<int> B(W+1);
vector liftmaxW(W+1,vector(16,0ll));
for(int i=1;i<=W;i++){
cin>>B[i];
liftmaxW[i][0]=B[i];
}
for(int bit=1;bit<16;bit++) {
for(int i=1;i<=W;i++) {
if(i+(1<<bit)-1>W)continue;
liftmaxW[i][bit]=max(liftmaxW[i][bit-1],liftmaxW[i+(1<<(bit-1))][bit-1]);
}
}
for(int i=1;i<=Q;i++) {
int s,t;
cin>>s>>t;
long long bestans = 0;
function<long long(int,int,int,int)> dfs = [&](int x,int y, int parx, int pary) {
if(x<1 or x>H or y<1 or y>W)return -1ll;
long long ans=0;
if(A[x]>B[y]) {
if(x!=parx or y-1!=pary) {
int newy = y;
for(int bit=15;bit>=0;bit--) {
if(newy-(1<<bit)<=0)continue;
if(liftmaxW[newy-(1<<bit)+1][bit]<A[x]) {
newy-=(1<<bit);
}
}
if(newy!=y)ans = max(dfs(x,newy,x,newy+1)+y-newy,ans);
}
if(x!=parx or y+1!=pary) {
int newy = y;
for(int bit=15;bit>=0;bit--) {
if(newy+(1<<bit)>W)continue;
if(liftmaxW[newy][bit]<A[x]) {
newy+=(1<<bit);
}
}
if(newy!=y)ans = max(dfs(x,newy,x,newy-1)+newy-y,ans);
}
} else {
if(x+1!=parx or y!=pary) {
int newx = x;
for(int bit=15;bit>=0;bit--) {
if(newx+(1<<bit)>H)continue;
if(liftmaxH[newx][bit]<B[y]) {
newx+=(1<<bit);
}
}
if(newx!=x)ans = max(dfs(newx,y,newx-1,y)+newx-x,ans);
}
if(x-1!=parx or y!=pary) {
int newx = x;
for(int bit=15;bit>=0;bit--) {
if(newx-(1<<bit)<=0)continue;
if(liftmaxH[newx-(1<<bit)+1][bit]<B[y]) {
newx-=(1<<bit);
}
}
if(newx!=x)ans = max(dfs(newx,y,newx+1,y)+x-newx,ans);
}
}
return ans;
};
bestans = max(bestans,dfs(s,t,s,t));
if(A[s]>B[t]) {
bestans=max(bestans,dfs(s-1,t,s,t)+1);
bestans=max(bestans,dfs(s+1,t,s,t)+1);
} else {
bestans=max(bestans,dfs(s,t-1,s,t)+1);
bestans=max(bestans,dfs(s,t+1,s,t)+1);
}
cout << bestans << '\n';
}
}
# | 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... |