Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int INF = INT_MAX;
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(NULL);
- int R, C;
- char mat[100][100];
- int dist[100][100];
- int drink_dist[4][4];
- int dx[] = {1, -1, 0, 0};
- int dy[] = {0, 0, 1, -1};
- vector<pair<int, int>> points;
- cin >> R >> C;
- pair<int, int> start, beach;
- vector<pair<int, int>> drinks;
- for (int i = 0; i < R; i++) {
- for (int j = 0; j < C; j++) {
- cin >> mat[i][j];
- if (mat[i][j] == 'S') {
- start = {i, j};
- } else if (mat[i][j] == 'B') {
- beach = {i, j};
- } else if (mat[i][j] == 'D') {
- drinks.push_back({i, j});
- }
- }
- }
- points.push_back(start);
- for (auto d : drinks) points.push_back(d);
- points.push_back(beach);
- auto bfs = [&](int start_idx) {
- queue<pair<int, int>> q;
- int start_x = points[start_idx].first;
- int start_y = points[start_idx].second;
- for (int i = 0; i < R; i++) {
- for (int j = 0; j < C; j++) {
- dist[i][j] = INF;
- }
- }
- dist[start_x][start_y] = 0;
- q.push({start_x, start_y});
- while (!q.empty()) {
- int x = q.front().first;
- int y = q.front().second;
- q.pop();
- for (int dir = 0; dir < 4; dir++) {
- int nx = x + dx[dir];
- int ny = y + dy[dir];
- if (nx >= 0 && nx < R && ny >= 0 && ny < C && mat[nx][ny] != '#' && dist[nx][ny] == INF) {
- dist[nx][ny] = dist[x][y] + 1;
- q.push({nx, ny});
- }
- }
- }
- for (int i = 0; i < points.size(); i++) {
- drink_dist[start_idx][i] = dist[points[i].first][points[i].second];
- }
- };
- for (int i = 0; i < points.size(); i++) {
- bfs(i);
- }
- vector<int> order;
- for (int i = 1; i <= drinks.size(); i++) {
- order.push_back(i);
- }
- int min_steps = INF;
- do {
- int current_steps = drink_dist[0][order[0]];
- for (int i = 1; i < order.size(); i++) {
- current_steps += drink_dist[order[i-1]][order[i]];
- }
- current_steps += drink_dist[order.back()][points.size() - 1];
- min_steps = min(min_steps, current_steps);
- } while (next_permutation(order.begin(), order.end()));
- if (min_steps >= INF) {
- cout << -1 << endl;
- } else {
- cout << min_steps << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement