kmjp's blog

競技プログラミング参加記です

yukicoder : No.3327 うるせぇ、ポリオミノぶつけんぞ

これは割とすんなり。
https://yukicoder.me/problems/no/3327

問題

N要素の整数列Aが与えられる。
以下のクエリを順次処理せよ。

  • 整数Xと方向が与えられる。
  • Aの要素でXより大きいもののうち、(方向で与えられたように)一番先頭または末尾に近い要素の位置番号を答え、その値を削除する。

解法

区間最大値を取れるSegTree上で二分探索すれば、対象の要素の位置をクエリあたりO(log^2 N)で答えられる。

template<class V,int NV> class SegTree_ma {
public:
	vector<V> val;
	static V const def=0;
	V comp(V l,V r){ return max(l,r);};
	
	SegTree_ma(){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]=v;
		while(entry>1) entry>>=1, val[entry]=comp(val[entry*2],val[entry*2+1]);
	}
};
SegTree_ma<int,1<<20> st;
int N,Q;


void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>N>>Q;
	FOR(i,N) {
		cin>>x;
		st.update(i,x);
	}
	while(Q--) {
		cin>>i>>x;
		if(st.getval(0,N)<=x) {
			cout<<-1<<endl;
			continue;
		}
		if(i==1) {
			int R=N;
			for(i=20;i>=0;i--) if(R-(1<<i)>0&&st.getval(0,R-(1<<i))>x) R-=1<<i;
			cout<<R<<endl;
			st.update(R-1,0);
		}
		else {
			int R=0;
			for(i=20;i>=0;i--) if(R+(1<<i)<N&&st.getval(R+(1<<i),N)>x) R+=1<<i;
			cout<<R+1<<endl;
			st.update(R,0);
		}
	}
}

まとめ

これは考え方が単純なので、★2.5でもいいかも?