제출 #896731

#제출 시각아이디문제언어결과실행 시간메모리
896731LCJLYMecho (IOI09_mecho)C++14
6 / 100
108 ms11812 KiB
#include <bits/stdc++.h>
using namespace std;

#define int long long
#define ld long double
#define show(x,y) cout << y << " " << #x << endl;
#define show2(x,y,i,j) cout << y << " " << #x << "  " << j << " " << #i << endl;
#define show3(x,y,i,j,p,q) cout << y << " " << #x << "  " << j << " " << #i << "  " << q << " " << #p << endl; 
#define show4(x,y) for(auto it:x) cout << it << " "; cout << #y << endl;
typedef pair<int,int>pii;
typedef pair<pii,pii>pi2;

void solve(){	
	int n,k;
	cin >> n >> k;
	
	string arr[n];
	for(int x=0;x<n;x++){
		cin >> arr[x];
	}
	
	int l=0;
	int r=n;
	int best=-1;
	int mid;
	
	pii start;
	pii done;
	
	int dist[n+5][n+5];
	memset(dist,-1,sizeof(dist));
	queue<pii>q;
	for(int x=0;x<n;x++){
		for(int y=0;y<n;y++){
			if(arr[x][y]=='H'){
				q.push({x,y});
				dist[x][y]=0;
			}
			else if(arr[x][y]=='M') start={x,y};
			else if(arr[x][y]=='D') done={x,y};
		}
	}
	
	pii dir[4]={
		{0,1},
		{0,-1},
		{1,0},
		{-1,0},
	};
	
	while(!q.empty()){
		pii cur=q.front();
		q.pop();
		for(auto it:dir){
			int newx=cur.first+it.first;
			int newy=cur.second+it.second;
			if(newx<0||newy<0||newx>=n||newy>=n) continue;
			if(dist[newx][newy]!=-1) continue;
			dist[newx][newy]=dist[cur.first][cur.second]+1;
			q.push({newx,newy});
		}
	}
	
	//for(int x=0;x<n;x++){
		//for(int y=0;y<n;y++){
			//cout << dist[x][y] << " ";
		//}
		//cout << "\n";
	//}

	
	while(l<=r){
		mid=(l+r)/2;
		
		int dist2[n][n];
		
		memset(dist2,-1,sizeof(dist2));
		dist2[start.first][start.second]=k*mid;
		q.push({start.first,start.second});
		
		while(!q.empty()){
			pii cur=q.front();
			q.pop();
			for(auto it:dir){
				int newx=cur.first+it.first;
				int newy=cur.second+it.second;
				if(newx<0||newy<0||newx>=n||newy>=n) continue;
				if(dist2[newx][newy]!=-1) continue;
				int hold=(dist2[cur.first][cur.second]+k)/k;
				if(dist[newx][newy]<hold) continue;
				dist2[newx][newy]=dist2[cur.first][cur.second]+1;
				q.push({newx,newy});
			}
		}
		
		if(dist2[done.first][done.second]!=-1){
			best=mid;
			l=mid+1;
		}
		else r=mid-1;
	}
	cout << best;
}

int32_t main(){										
	ios::sync_with_stdio(0);	
	cin.tie(0);
	//freopen("out.txt", "w", stdout);
	int t=1;
	//cin >> t;
	while(t--){
		solve();
	}	
}





		


		
		
	
#Verdict Execution timeMemoryGrader output
Fetching results...