This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define sz size()
#define ll long long
// yokary saga asak cepe
// 0 1 2 3
const int N = 505;
int aa[] = {-1, 0, 1, 0};
int bb[] = {0, 1, 0, -1};
pair <int, int> a1, b1;
int n, m, k, dis[N][N][N];
bool dur[N][N][4], vis[N][N][N];
char a[N][N];
vector <pair <int, int>> v;
pair <int, int> direct[N][N][4];
bool durmalymy (int x, int y) {
if (min (x, y) < 1 or x > n or y > m or a[x][y] == 'x') return 1;
return 0;
}
pair <int, int> ugur (int x, int y, int val) {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
for (int k = 0; k < 4; ++k) {
dur[i][j][k] = 0;
}
}
}
while (1) {
if (a[x][y] == 'A') {
val--;
}
else if (a[x][y] == 'C') {
val++;
}
if (dur[x][y][val]) {
x = y = 0;
break;
}
val += 4;val %= 4;
dur[x][y][val] = 1;
if (durmalymy (x + aa[val], y + bb[val])) break;
x += aa[val];y += bb[val];
}
return {x, y};
}
int main () {
// freopen ("input.txt", "r", stdin);
cin >> k >> m >> n;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
cin >> a[i][j];
if (a[i][j] >= '1' and a[i][j] <= '9') v.pb ({i, j});
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (a[i][j] != 'x') {
for (int l = 0; l < 4; ++l) {
direct[i][j][l] = ugur(i, j, l);
}
}
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
for (int l = 1; l <= k; ++l) {
dis[i][j][l] = 1e9;
}
}
}
queue <pair <int, int>> q;
for (int j = 0; j < k; ++j) {
q.push({v[j].ff, v[j].ss});
dis[v[j].ff][v[j].ss][j + 1] = 0;
vis[0][0][j + 1] = vis[v[j].ff][v[j].ss][j + 1] = 1;
while (!q.empty()) {
auto op = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
auto x = direct[op.ff][op.ss][i];
if (vis[x.ff][x.ss][j + 1]) continue;
q.push({x.ff, x.ss});
dis[x.ff][x.ss][j + 1] = dis[op.ff][op.ss][j + 1] + 1;
vis[x.ff][x.ss][j + 1] = 1;
}
}
}
int jog = 1e9;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
ll sum = 0;
for (int l = 1; l <= k; ++l) {
sum += dis[i][j][l];
}
if (sum < (ll)1e9) jog = min (jog, (int)sum);
}
}
if (jog == 1e9) jog = -1;
cout << jog;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |