kmjp's blog

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

yukicoder : No.3599 Queen Moving Query

移動中に壁があったらダメなんだ。
https://yukicoder.me/problems/no/3599

問題

H*Wのグリッドと、クイーンの初期位置が与えられる。
一部セルは移動不可であり、クイーンが1手で移動する際、移動先のマスが移動可であっても、その間に移動不可マスがあると移動できない。

以下のクエリに答えよ。

  • セルの位置とターン数Tが与えられる。クイーンをちょうどT回動かして、その位置にクイーンを停止させられるか。

解法

クイーンが初期位置から動けない場合は例外ケースとする。
クイーンが移動できる2セル間を往復すれば、移動回数を2稼げる。

よって
D(r,c,p) := セル(r,c)に至る手順のうち、移動回数の偶奇がpに一致する場合の最小ターン数
とすると、クエリ(r,c,T)に対しD(r,c,T%2)がT以下かどうかで判定できる。
D(r,c,p)はBFSの要領で求められる。

int H,W,SY,SX;
string S[202020];
vector<ll> dp[2][10][202020];
int Q,T;
map<int,vector<pair<int,int>>> Ys[2],Xs[2],YpX[2],YmX[2];

int dy[]={-1,-1,-1,0,0,0,1,1,1};
int dx[]={-1,0,1,-1,0,1,-1,0,1};

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>H>>W>>SY>>SX;
	SY--,SX--;
	FOR(y,H) {
		cin>>S[y];
		FOR(i,2) FOR(j,10) dp[i][j][y].resize(W,1LL<<60);
	}
	dp[0][9][SY][SX]=0;
	deque<int> Q;
	Q.push_back({9*H*W+SY*W+SX});
	while(Q.size()) {
		int step=Q.front()/(H*W*10);
		int prev=Q.front()/(H*W)%10;
		int cy=Q.front()%(H*W)/W;
		int cx=Q.front()%W;
		Q.pop_front();
		if(prev==4||prev==9) {
			FOR(i,9) if(i!=4) {
				int ty=cy+dy[i];
				int tx=cx+dx[i];
				if(ty>=0&&ty<H&&tx>=0&&tx<W&&S[ty][tx]=='.'&&chmin(dp[step^1][i][ty][tx],dp[step][prev][cy][cx]+1)) Q.push_back((step^1)*H*W*10+i*H*W+ty*W+tx);
			}
		}
		else {
			if(chmin(dp[step][4][cy][cx],dp[step][prev][cy][cx])) Q.push_front(step*H*W*10+4*H*W+cy*W+cx);
			int ty=cy+dy[prev];
			int tx=cx+dx[prev];
			if(ty>=0&&ty<H&&tx>=0&&tx<W&&S[ty][tx]=='.'&&chmin(dp[step][prev][ty][tx],dp[step][prev][cy][cx])) Q.push_front(step*H*W*10+prev*H*W+ty*W+tx);
		}
		
		
	}
	cin>>x;
	while(x--) {
		cin>>SY>>SX>>T;
		if(dp[T%2][4][SY-1][SX-1]<=T) cout<<"Yes"<<endl;
		else cout<<"No"<<endl;
	}
}

まとめ

これは割とすんなり。