kmjp's blog

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

yukicoder : No.2242 Cities and Teleporters

これは割と典型より。
https://yukicoder.me/problems/no/2242

問題

N個の町があり、それぞれの標高H[i]が与えられる。
各町にはテレポーターがあり、それにのると標高T[i]以下の町に移動できる。

2つの町からなるクエリが与えられる。
前者の町から後者の町に移動可能か、可能ならテレポーターの使用回数の最小値を求めよ。

解法

ダブリングで解く。
f(x) := 標高x以下の町に移動可能な状態で、もう1回テレポーターを使うと最大どの標高まで移動できるか
をあらかじめ求めておき、ダブリングしておけば、クエリ毎にO(logN)で解を答えられる。

int N;
int H[202020];
int T[202020];
int R[202020];
int D[202020][20];
int Q;

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>N;
	vector<pair<int,int>> Vs;
	FOR(i,N) {
		cin>>H[i];
		Vs.push_back({H[i],i});
	}
	FOR(i,N) {
		cin>>T[i];
	}
	sort(ALL(Vs));
	int ma=0;
	FOR(i,N) R[Vs[i].second]=i;
	
	FOR(i,N) {
		x=Vs[i].second;
		ma=max(ma,T[x]);
		D[i][0]=lower_bound(ALL(Vs),make_pair(ma+1,0))-Vs.begin()-1;
		D[i][0]=max(D[i][0],0);
	}
	
	FOR(i,18) {
		FOR(j,N) D[j][i+1]=D[D[j][i]][i];
	}
	
	cin>>Q;
	while(Q--) {
		cin>>x>>y;
		x--,y--;
		if(H[y]<=T[x]) {
			cout<<1<<endl;
			continue;
		}
		x=lower_bound(ALL(Vs),make_pair(T[x]+1,0))-Vs.begin()-1;
		if(x<0) {
			cout<<-1<<endl;
			continue;
		}
		int ret=2;
		if(D[x][18]<R[y]) {
			cout<<-1<<endl;
		}
		else {
			for(i=17;i>=0;i--) {
				if(D[x][i]<R[y]) {
					ret+=1<<i;
					x=D[x][i];
				}
			}
			cout<<ret<<endl;
		}
	}
	
}

まとめ

なんか実装にちょっと手間取った。