제출 #254317

#제출 시각아이디문제언어결과실행 시간메모리
254317sandovalMecho (IOI09_mecho)C++11
100 / 100
209 ms8916 KiB
#include <bits/stdc++.h>

using namespace std;
using ii = pair<int,int>;
using ll = long long;

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

constexpr int MAXS = 5+800;
constexpr int INF = 1e8;
char c[MAXS][MAXS];
int N,S, tb[MAXS][MAXS];

bool ok(int x, int y) {
  return x >= 0 && y >= 0 && x < N && y < N;
}

void bfs_bees() {
  queue<ii> q;
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      if (c[i][j] == 'H') {
        q.push({i,j});
        tb[i][j] = 0;
      } else {
        tb[i][j] = 10*INF;
      }
    }
  }

  while (!q.empty()) {
    auto u = q.front(); q.pop();
    for (int k = 0; k < 4; ++k) {
      int newx = u.first+dx[k], newy = u.second+dy[k];
      if (ok(newx, newy) && 1+tb[u.first][u.second] < tb[newx][newy] && (c[newx][newy] == 'G' || c[newx][newy] == 'M')) {
        q.push({newx, newy});
        tb[newx][newy] = 1+tb[u.first][u.second];
      }
    }
  }
}


ii dist[MAXS][MAXS];
bool can(const ii& source, const ii& target, int t) {
  if (t >= tb[source.first][source.second]) return false;
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      dist[i][j] = {10*INF, 0};
    }
  }

  queue<array<int,2>> q; q.push({source.first, source.second});
  dist[source.first][source.second] = {t, S};

  while (!q.empty()) {
    auto u = q.front(); q.pop();
    if (u[0] == target.first && u[1] == target.second) return true;
    for (int k = 0; k < 4; ++k) {
      int newx = u[0]+dx[k], newy = u[1]+dy[k];
      ii newcost = dist[u[0]][u[1]];
      newcost.second--;

      if (newcost.second <= 0) {
        newcost.first++;
        newcost.second = S;
      }

      if (ok(newx, newy) && (c[newx][newy] == 'G' || c[newx][newy] == 'D' || c[newx][newy] == 'M') && newcost.first < tb[newx][newy] && newcost.first < dist[newx][newy].first) {
        q.push({newx, newy});
        dist[newx][newy] = newcost;
      }
    }
  }
  return false;
}

int main() {
  ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
  cin >> N >> S;
  ii start, target;
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      cin >> c[i][j];
      if (c[i][j] == 'M') {
        start = {i,j};
      } else if (c[i][j] == 'D') {
        target = {i,j};
      }
    }
  }

  bfs_bees();

  int low = 0, high = INF, best = -1;
  while (low <= high) {
    int mid = (low+high) >> 1;
    if (can(start, target, mid)) {
      low = 1+mid;
      best = mid;
    } else {
      high = mid-1;
    }
  }
  cout << best << '\n';
  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...