Submission #1165130

#TimeUsernameProblemLanguageResultExecution timeMemory
1165130AgageldiRobots (APIO13_robots)C++20
10 / 100
0 ms328 KiB
#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define N 600005
#define pb push_back
#define ff first
#define ss second
#define all(x) x.begin(),x.end()
#define SZ(s) (int)s.size()

ll n, w, h, dp[500][500][10], answer = INT_MAX;
pair <int,int> location[10];
char a[500][500];

pair<int,int> f(int i,int j,int direction) {
	while(direction == 1 && j < w && a[i][j + 1] != 'x') j++;
	while(direction == 2 && j > 1 && a[i][j - 1] != 'x') j--;
	while(direction == 3 && i > 1 && a[i - 1][j] != 'x') i--;
	while(direction == 4 && i < h && a[i + 1][j] != 'x') i++;
	return {i,j};
}

void solve(int i,int j,int direction,int robot,int op) {
	if(dp[i][j][robot] < op) return;
	dp[i][j][robot] = op;
	pair<int,int> j1 = f(i,j,direction);
	for(int x = 1; x <= 3; x++) {
		solve(j1.ff,j1.ss,((direction+x>4) ? (direction+x)%4 : direction+x), robot, op+1);
	}
}

int main () {
	cin.tie(0)->sync_with_stdio(0);
	cin >> n >> h >> w;
	for(int i = 1; i <= w; i++) {
		for(int j = 1; j <= h; j++) {
			cin >> a[i][j];
			for(int k = 1; k <= n; k++){
				dp[i][j][k] = INT_MAX;
			}
			if(a[i][j] - 48 >= 1 && a[i][j] - 48 <= 9) {
				location[a[i][j] - 48] = {i,j};
			}
			if(a[i][j] != 'x') a[i][j] = '.';
		}
	}
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= 4; j++) {
			solve(location[i].ff, location[i].ss, j, i, 0);
		}
	}
	for(int i = 1; i <= w; i++) {
		for(int j = 1; j <= h; j++) {
			ll ans = 0, tr = 0;
			for(int k = 1; k <= n; k++) {
				if(dp[i][j][k] == INT_MAX) {
					tr = 1;
					break;
				}	
				ans += dp[i][j][k];
			}
			if(tr) continue;
			answer = min(ans,answer);
		}
	}
	cout << (answer == INT_MAX ? -1 : answer) << '\n';
	return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...