これは余り迷わなかった。
https://yukicoder.me/problems/no/1332
問題
整数列Xが与えられる。
以下のクエリに順次答えよ。
- 区間[L...R]と整数Yが指定される。k∈[L,R]のうちmin(|X[k]-Y|)を答えよ。
解法
X[k]≦Yのケースを考えよう。X[k]とYの符号を反転させれば、X[k]≧Yのケースもカバーできる。
区間最小値を求めるSegTreeを使う。
数列の要素とクエリをX[k]及びYの昇順に並べ替えて置き、順次処理する。
SegTreeは初期値をマイナス無限大にしておく。
- X[k]を処理する場合、SegTree上でk番目の要素をX[k]にする
- クエリを処理する場合、SegTreeで区間最大値を求めればYに最も近いX[k]がわかるので、そのようなY-X[k]を解の候補とする
int N; int X[303030]; int Q; int L[303030],R[303030],Y[303030]; ll ret[303030]; vector<pair<int,int>> O[2]; template<class V,int NV> class SegTree_1 { public: vector<V> val; static V const def=-(1LL<<40); V comp(V l,V r){ return max(l,r);}; SegTree_1(){val=vector<V>(NV*2,def);}; V getval(int x,int y,int l=0,int r=NV,int k=1) { // x<=i<y if(r<=x || y<=l) return def; if(x<=l && r<=y) return val[k]; return comp(getval(x,y,l,(l+r)/2,k*2),getval(x,y,(l+r)/2,r,k*2+1)); } void update(int entry, V v) { entry += NV; val[entry]=comp(v,val[entry]); //上書きかチェック while(entry>1) entry>>=1, val[entry]=comp(val[entry*2],val[entry*2+1]); } }; SegTree_1<ll,1<<20> st[2]; void solve() { int i,j,k,l,r,x,y; string s; cin>>N; FOR(i,N) { cin>>X[i]; O[0].push_back({X[i],i}); O[1].push_back({-X[i],i}); } cin>>Q; FOR(i,Q) { cin>>L[i]>>R[i]>>Y[i]; L[i]--; O[0].push_back({Y[i],N+i}); O[1].push_back({-Y[i],N+i}); ret[i]=1LL<<40; } FOR(i,2) { sort(ALL(O[i])); FORR2(v,e,O[i]) { if(e<N) { st[i].update(e,v); } else { e-=N; ret[e]=min(ret[e],v-st[i].getval(L[e],R[e])); } } } FOR(i,Q) cout<<ret[i]<<endl; }
まとめ
なんでこの回妙にPythonに厳しい時間設定なんだろうな。