output
stringlengths
52
181k
instruction
stringlengths
296
182k
#include <bits/stdc++.h> int main() { int h1, h2; scanf("%d %d", &h1, &h2); int a, b; scanf("%d %d", &a, &b); if (h2 - h1 < a * 8) { printf("0"); return 0; } if ((h2 - h1 > a * 8) && (a <= b)) { printf("-1"); return 0; } int day = 0; int dayend, nightend; while (1) { if (day == 0) { dayend = h1 + a * 8; } else { dayend = nightend + a * 12; } if (dayend >= h2) { printf("%d", day); return 0; } nightend = dayend - b * 12; day++; } return 0; }
### Prompt Develop a solution in cpp to the problem described below: The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h1 cm from the ground. On the height h2 cm (h2 > h1) on the same tree hung an apple and the caterpillar was crawling to the apple. Gabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by a cm per hour by day and slips down by b cm per hour by night. In how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at 10 am and finishes at 10 pm. Gabriel's classes finish at 2 pm. You can consider that Gabriel noticed the caterpillar just after the classes at 2 pm. Note that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple. Input The first line contains two integers h1, h2 (1 ≀ h1 < h2 ≀ 105) β€” the heights of the position of the caterpillar and the apple in centimeters. The second line contains two integers a, b (1 ≀ a, b ≀ 105) β€” the distance the caterpillar goes up by day and slips down by night, in centimeters per hour. Output Print the only integer k β€” the number of days Gabriel should wait to return to the forest and see the caterpillar getting the apple. If the caterpillar can't get the apple print the only integer - 1. Examples Input 10 30 2 1 Output 1 Input 10 13 1 1 Output 0 Input 10 19 1 2 Output -1 Input 1 50 5 4 Output 1 Note In the first example at 10 pm of the first day the caterpillar gets the height 26. At 10 am of the next day it slips down to the height 14. And finally at 6 pm of the same day the caterpillar gets the apple. Note that in the last example the caterpillar was slipping down under the ground and getting the apple on the next day. ### Response ```cpp #include <bits/stdc++.h> int main() { int h1, h2; scanf("%d %d", &h1, &h2); int a, b; scanf("%d %d", &a, &b); if (h2 - h1 < a * 8) { printf("0"); return 0; } if ((h2 - h1 > a * 8) && (a <= b)) { printf("-1"); return 0; } int day = 0; int dayend, nightend; while (1) { if (day == 0) { dayend = h1 + a * 8; } else { dayend = nightend + a * 12; } if (dayend >= h2) { printf("%d", day); return 0; } nightend = dayend - b * 12; day++; } return 0; } ```
#include <bits/stdc++.h> #pragma warning(disable : 4996) using namespace std; using LL = int64_t; using pii = pair<int, int>; const double PI = 2 * asin(1); int g_h1, g_h2, g_a, g_b; void pretreat() {} void input() { cin >> g_a >> g_b; } void solve() { int t = g_h1 + g_a * 8; if (t >= g_h2) { puts("0"); return; } if (g_a > g_b) { printf("%d\n", ((g_h2 - g_h1 - (8 * g_a)) + (12 * (g_a - g_b)) - 1) / (12 * (g_a - g_b))); } else { puts("-1"); } } int main() { pretreat(); while (cin >> g_h1 >> g_h2) { input(); solve(); } return 0; }
### Prompt In Cpp, your task is to solve the following problem: The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h1 cm from the ground. On the height h2 cm (h2 > h1) on the same tree hung an apple and the caterpillar was crawling to the apple. Gabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by a cm per hour by day and slips down by b cm per hour by night. In how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at 10 am and finishes at 10 pm. Gabriel's classes finish at 2 pm. You can consider that Gabriel noticed the caterpillar just after the classes at 2 pm. Note that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple. Input The first line contains two integers h1, h2 (1 ≀ h1 < h2 ≀ 105) β€” the heights of the position of the caterpillar and the apple in centimeters. The second line contains two integers a, b (1 ≀ a, b ≀ 105) β€” the distance the caterpillar goes up by day and slips down by night, in centimeters per hour. Output Print the only integer k β€” the number of days Gabriel should wait to return to the forest and see the caterpillar getting the apple. If the caterpillar can't get the apple print the only integer - 1. Examples Input 10 30 2 1 Output 1 Input 10 13 1 1 Output 0 Input 10 19 1 2 Output -1 Input 1 50 5 4 Output 1 Note In the first example at 10 pm of the first day the caterpillar gets the height 26. At 10 am of the next day it slips down to the height 14. And finally at 6 pm of the same day the caterpillar gets the apple. Note that in the last example the caterpillar was slipping down under the ground and getting the apple on the next day. ### Response ```cpp #include <bits/stdc++.h> #pragma warning(disable : 4996) using namespace std; using LL = int64_t; using pii = pair<int, int>; const double PI = 2 * asin(1); int g_h1, g_h2, g_a, g_b; void pretreat() {} void input() { cin >> g_a >> g_b; } void solve() { int t = g_h1 + g_a * 8; if (t >= g_h2) { puts("0"); return; } if (g_a > g_b) { printf("%d\n", ((g_h2 - g_h1 - (8 * g_a)) + (12 * (g_a - g_b)) - 1) / (12 * (g_a - g_b))); } else { puts("-1"); } } int main() { pretreat(); while (cin >> g_h1 >> g_h2) { input(); solve(); } return 0; } ```
#include <bits/stdc++.h> using namespace std; int h1, h2, a, b, k, day, delta; int main() { scanf("%d %d", &h1, &h2); scanf("%d %d", &a, &b); delta = a - b; if (delta <= 0) { if (a * 8 + h1 >= h2) printf("0\n"); else printf("-1\n"); } else { k = h2 - h1 - a * 8; if (k > 0) { day = (k - 1) / (delta * 12) + 1; printf("%d\n", day); } else printf("0\n"); } return 0; }
### Prompt Develop a solution in Cpp to the problem described below: The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h1 cm from the ground. On the height h2 cm (h2 > h1) on the same tree hung an apple and the caterpillar was crawling to the apple. Gabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by a cm per hour by day and slips down by b cm per hour by night. In how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at 10 am and finishes at 10 pm. Gabriel's classes finish at 2 pm. You can consider that Gabriel noticed the caterpillar just after the classes at 2 pm. Note that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple. Input The first line contains two integers h1, h2 (1 ≀ h1 < h2 ≀ 105) β€” the heights of the position of the caterpillar and the apple in centimeters. The second line contains two integers a, b (1 ≀ a, b ≀ 105) β€” the distance the caterpillar goes up by day and slips down by night, in centimeters per hour. Output Print the only integer k β€” the number of days Gabriel should wait to return to the forest and see the caterpillar getting the apple. If the caterpillar can't get the apple print the only integer - 1. Examples Input 10 30 2 1 Output 1 Input 10 13 1 1 Output 0 Input 10 19 1 2 Output -1 Input 1 50 5 4 Output 1 Note In the first example at 10 pm of the first day the caterpillar gets the height 26. At 10 am of the next day it slips down to the height 14. And finally at 6 pm of the same day the caterpillar gets the apple. Note that in the last example the caterpillar was slipping down under the ground and getting the apple on the next day. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int h1, h2, a, b, k, day, delta; int main() { scanf("%d %d", &h1, &h2); scanf("%d %d", &a, &b); delta = a - b; if (delta <= 0) { if (a * 8 + h1 >= h2) printf("0\n"); else printf("-1\n"); } else { k = h2 - h1 - a * 8; if (k > 0) { day = (k - 1) / (delta * 12) + 1; printf("%d\n", day); } else printf("0\n"); } return 0; } ```
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll inf = 1e18; vector<int> adj[100005], adj1[100005]; ll cnt, ans; bool vis[100005]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int h1, h2, a, b, diff, av, res; cin >> h1 >> h2 >> a >> b; diff = h2 - h1; if (a <= b) { if (8 * a >= diff) cout << 0 << '\n'; else cout << -1 << '\n'; } else { av = a - b; diff -= (8 * a); if (diff <= 0) return cout << 0, 0; res = ceil(double(diff) / (12 * av)); cout << res; } return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h1 cm from the ground. On the height h2 cm (h2 > h1) on the same tree hung an apple and the caterpillar was crawling to the apple. Gabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by a cm per hour by day and slips down by b cm per hour by night. In how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at 10 am and finishes at 10 pm. Gabriel's classes finish at 2 pm. You can consider that Gabriel noticed the caterpillar just after the classes at 2 pm. Note that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple. Input The first line contains two integers h1, h2 (1 ≀ h1 < h2 ≀ 105) β€” the heights of the position of the caterpillar and the apple in centimeters. The second line contains two integers a, b (1 ≀ a, b ≀ 105) β€” the distance the caterpillar goes up by day and slips down by night, in centimeters per hour. Output Print the only integer k β€” the number of days Gabriel should wait to return to the forest and see the caterpillar getting the apple. If the caterpillar can't get the apple print the only integer - 1. Examples Input 10 30 2 1 Output 1 Input 10 13 1 1 Output 0 Input 10 19 1 2 Output -1 Input 1 50 5 4 Output 1 Note In the first example at 10 pm of the first day the caterpillar gets the height 26. At 10 am of the next day it slips down to the height 14. And finally at 6 pm of the same day the caterpillar gets the apple. Note that in the last example the caterpillar was slipping down under the ground and getting the apple on the next day. ### Response ```cpp #include <bits/stdc++.h> using namespace std; using ll = long long; const ll inf = 1e18; vector<int> adj[100005], adj1[100005]; ll cnt, ans; bool vis[100005]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int h1, h2, a, b, diff, av, res; cin >> h1 >> h2 >> a >> b; diff = h2 - h1; if (a <= b) { if (8 * a >= diff) cout << 0 << '\n'; else cout << -1 << '\n'; } else { av = a - b; diff -= (8 * a); if (diff <= 0) return cout << 0, 0; res = ceil(double(diff) / (12 * av)); cout << res; } return 0; } ```
#include <bits/stdc++.h> using namespace std; int treas[310][310]; long long dp[310][310]; long long d[310][310]; vector<pair<int, int> > G[110000]; vector<pair<long long, pair<int, int> > > lst; queue<pair<long long, pair<int, int> > > bfs; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; long long n, m; long long Dist(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } int main() { ios_base::sync_with_stdio(0); int p, fx, fy; cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> treas[i][j]; G[treas[i][j]].push_back({i, j}); if (treas[i][j] == p) fx = i, fy = j; if (treas[i][j] == 1) dp[i][j] = i + j; } for (int i = 2; i <= p; i++) { long long cur_size = G[i].size(); long long prev_size = G[i - 1].size(); if (cur_size * prev_size <= n * m) { for (int j = 0; j < cur_size; j++) { int cur_x = G[i][j].first; int cur_y = G[i][j].second; dp[cur_x][cur_y] = 1e9; for (int k = 0; k < prev_size; k++) { int prev_x = G[i - 1][k].first; int prev_y = G[i - 1][k].second; dp[cur_x][cur_y] = min(dp[cur_x][cur_y], dp[prev_x][prev_y] + Dist(cur_x, cur_y, prev_x, prev_y)); } } } else { lst.clear(); for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) d[j][k] = -1; for (int j = 0; j < prev_size; j++) { int prev_x = G[i - 1][j].first; int prev_y = G[i - 1][j].second; lst.push_back({dp[prev_x][prev_y], {prev_x, prev_y}}); } sort(lst.begin(), lst.end()); int ptr = 1; bfs.push(lst[0]); d[lst[0].second.first][lst[0].second.second] = lst[0].first; while (!bfs.empty()) { int x = bfs.front().second.first; int y = bfs.front().second.second; long long val = bfs.front().first; bfs.pop(); while (ptr < lst.size() && lst[ptr].first <= val) bfs.push(lst[ptr++]); int X, Y; for (int k = 0; k < 4; k++) { X = x + dir[k][0]; Y = y + dir[k][1]; if (X >= 0 && X <= n && Y >= 0 && Y < m && d[X][Y] == -1) { d[X][Y] = val + 1; bfs.push({val + 1, {X, Y}}); } } } for (int j = 0; j < cur_size; j++) { int x = G[i][j].first; int y = G[i][j].second; dp[x][y] = d[x][y]; } } } cout << dp[fx][fy] << "\n"; return 0; }
### Prompt Develop a solution in CPP to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int treas[310][310]; long long dp[310][310]; long long d[310][310]; vector<pair<int, int> > G[110000]; vector<pair<long long, pair<int, int> > > lst; queue<pair<long long, pair<int, int> > > bfs; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; long long n, m; long long Dist(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } int main() { ios_base::sync_with_stdio(0); int p, fx, fy; cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> treas[i][j]; G[treas[i][j]].push_back({i, j}); if (treas[i][j] == p) fx = i, fy = j; if (treas[i][j] == 1) dp[i][j] = i + j; } for (int i = 2; i <= p; i++) { long long cur_size = G[i].size(); long long prev_size = G[i - 1].size(); if (cur_size * prev_size <= n * m) { for (int j = 0; j < cur_size; j++) { int cur_x = G[i][j].first; int cur_y = G[i][j].second; dp[cur_x][cur_y] = 1e9; for (int k = 0; k < prev_size; k++) { int prev_x = G[i - 1][k].first; int prev_y = G[i - 1][k].second; dp[cur_x][cur_y] = min(dp[cur_x][cur_y], dp[prev_x][prev_y] + Dist(cur_x, cur_y, prev_x, prev_y)); } } } else { lst.clear(); for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) d[j][k] = -1; for (int j = 0; j < prev_size; j++) { int prev_x = G[i - 1][j].first; int prev_y = G[i - 1][j].second; lst.push_back({dp[prev_x][prev_y], {prev_x, prev_y}}); } sort(lst.begin(), lst.end()); int ptr = 1; bfs.push(lst[0]); d[lst[0].second.first][lst[0].second.second] = lst[0].first; while (!bfs.empty()) { int x = bfs.front().second.first; int y = bfs.front().second.second; long long val = bfs.front().first; bfs.pop(); while (ptr < lst.size() && lst[ptr].first <= val) bfs.push(lst[ptr++]); int X, Y; for (int k = 0; k < 4; k++) { X = x + dir[k][0]; Y = y + dir[k][1]; if (X >= 0 && X <= n && Y >= 0 && Y < m && d[X][Y] == -1) { d[X][Y] = val + 1; bfs.push({val + 1, {X, Y}}); } } } for (int j = 0; j < cur_size; j++) { int x = G[i][j].first; int y = G[i][j].second; dp[x][y] = d[x][y]; } } } cout << dp[fx][fy] << "\n"; return 0; } ```
#include <bits/stdc++.h> using namespace std; vector<int> Adj[301]; vector<int> Col[301]; vector<pair<int, int> > To[301 * 301]; inline int dist(pair<int, int> A, pair<int, int> B) { return abs(A.first - B.first) + abs(A.second - B.second); } int D[301][301]; const int INF = (int)1e9; int main() { int N, M, i, j, P, x; scanf("%d%d%d", &N, &M, &P); for (i = 0; i < N; ++i) for (j = 0; j < M; ++j) { scanf("%d", &x); To[x].push_back({i, j}); D[i][j] = INF; } pair<int, int> z = *To[P].begin(); D[z.first][z.second] = 0; Adj[z.first].push_back(z.second); Col[z.second].push_back(z.first); for (x = P - 1; x >= 1; --x) { for (auto u : To[x]) { for (i = 0; i < N; ++i) { auto a = lower_bound(Adj[i].begin(), Adj[i].begin(), u.second); if (a != Adj[i].end()) D[u.first][u.second] = min(D[u.first][u.second], D[i][*a] + dist(u, {i, *a})); if (a != Adj[i].begin()) { --a; D[u.first][u.second] = min(D[u.first][u.second], D[i][*a] + dist(u, {i, *a})); } } for (i = 0; i < M; ++i) { auto a = lower_bound(Col[i].begin(), Col[i].end(), u.first); if (a != Col[i].end()) D[u.first][u.second] = min(D[u.first][u.second], D[*a][i] + dist(u, {*a, i})); if (a != Col[i].begin()) { --a; D[u.first][u.second] = min(D[u.first][u.second], D[*a][i] + dist(u, {*a, i})); } } } for (i = 0; i < N; ++i) Adj[i].clear(); for (i = 0; i < M; ++i) Col[i].clear(); for (auto v : To[x]) { Col[v.second].push_back(v.first); Adj[v.first].push_back(v.second); } } int ans = INF; for (auto v : To[1]) ans = min(ans, D[v.first][v.second] + dist(v, {0, 0})); printf("%d\n", ans); return 0; }
### Prompt Develop a solution in Cpp to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<int> Adj[301]; vector<int> Col[301]; vector<pair<int, int> > To[301 * 301]; inline int dist(pair<int, int> A, pair<int, int> B) { return abs(A.first - B.first) + abs(A.second - B.second); } int D[301][301]; const int INF = (int)1e9; int main() { int N, M, i, j, P, x; scanf("%d%d%d", &N, &M, &P); for (i = 0; i < N; ++i) for (j = 0; j < M; ++j) { scanf("%d", &x); To[x].push_back({i, j}); D[i][j] = INF; } pair<int, int> z = *To[P].begin(); D[z.first][z.second] = 0; Adj[z.first].push_back(z.second); Col[z.second].push_back(z.first); for (x = P - 1; x >= 1; --x) { for (auto u : To[x]) { for (i = 0; i < N; ++i) { auto a = lower_bound(Adj[i].begin(), Adj[i].begin(), u.second); if (a != Adj[i].end()) D[u.first][u.second] = min(D[u.first][u.second], D[i][*a] + dist(u, {i, *a})); if (a != Adj[i].begin()) { --a; D[u.first][u.second] = min(D[u.first][u.second], D[i][*a] + dist(u, {i, *a})); } } for (i = 0; i < M; ++i) { auto a = lower_bound(Col[i].begin(), Col[i].end(), u.first); if (a != Col[i].end()) D[u.first][u.second] = min(D[u.first][u.second], D[*a][i] + dist(u, {*a, i})); if (a != Col[i].begin()) { --a; D[u.first][u.second] = min(D[u.first][u.second], D[*a][i] + dist(u, {*a, i})); } } } for (i = 0; i < N; ++i) Adj[i].clear(); for (i = 0; i < M; ++i) Col[i].clear(); for (auto v : To[x]) { Col[v.second].push_back(v.first); Adj[v.first].push_back(v.second); } } int ans = INF; for (auto v : To[1]) ans = min(ans, D[v.first][v.second] + dist(v, {0, 0})); printf("%d\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MaxN = 305, Inf = 0x3f3f3f3f; const int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; queue<pair<int, int> > Q; vector<pair<int, int> > Chest[MaxN * MaxN]; int n, m, p; int dp[MaxN][MaxN], mat[MaxN][MaxN], Distance[MaxN][MaxN]; inline void ClearQ() { while (Q.size()) { Q.pop(); } } inline bool InBounds(int x, int y) { return x >= 1 and x <= n and y >= 1 and y <= m; } inline bool cmp(const pair<int, int> &a, const pair<int, int> &b) { return dp[a.first][a.second] < dp[b.first][b.second]; } void Lee(int st, int ed) { ClearQ(); memset(Distance, 0, sizeof Distance); sort(Chest[st].begin(), Chest[st].end(), cmp); Q.push(Chest[st][0]); Distance[Chest[st][0].first][Chest[st][0].second] = dp[Chest[st][0].first][Chest[st][0].second]; int toAdd = 1; while (Q.size()) { pair<int, int> node = Q.front(); Q.pop(); for (int i = 0; i < 4; ++i) { int xNew = node.first + dir[i][0]; int yNew = node.second + dir[i][1]; if (InBounds(xNew, yNew) and !Distance[xNew][yNew]) { Distance[xNew][yNew] = Distance[node.first][node.second] + 1; for (; toAdd < (int)Chest[st].size() and dp[Chest[st][toAdd].first][Chest[st][toAdd].second] <= Distance[xNew][yNew]; ++toAdd) { Distance[Chest[st][toAdd].first][Chest[st][toAdd].second] = dp[Chest[st][toAdd].first][Chest[st][toAdd].second]; Q.push(Chest[st][toAdd]); } Q.push(make_pair(xNew, yNew)); } } } for (auto it : Chest[ed]) { dp[it.first][it.second] = Distance[it.first][it.second]; } } int main() { ios::sync_with_stdio(false); cin >> n >> m >> p; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { cin >> mat[i][j]; Chest[mat[i][j]].push_back(make_pair(i, j)); } } for (auto it : Chest[1]) { dp[it.first][it.second] = it.first - 1 + it.second - 1; } for (int i = 2; i <= p; ++i) { if (Chest[i].size() * Chest[i - 1].size() <= m * n) { for (auto it2 : Chest[i]) { int currAns = Inf; for (auto it1 : Chest[i - 1]) { currAns = min(currAns, dp[it1.first][it1.second] + abs(it2.first - it1.first) + abs(it2.second - it1.second)); } dp[it2.first][it2.second] = currAns; } } else { Lee(i - 1, i); } } cout << dp[Chest[p][0].first][Chest[p][0].second] << '\n'; return 0; }
### Prompt Please formulate a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MaxN = 305, Inf = 0x3f3f3f3f; const int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; queue<pair<int, int> > Q; vector<pair<int, int> > Chest[MaxN * MaxN]; int n, m, p; int dp[MaxN][MaxN], mat[MaxN][MaxN], Distance[MaxN][MaxN]; inline void ClearQ() { while (Q.size()) { Q.pop(); } } inline bool InBounds(int x, int y) { return x >= 1 and x <= n and y >= 1 and y <= m; } inline bool cmp(const pair<int, int> &a, const pair<int, int> &b) { return dp[a.first][a.second] < dp[b.first][b.second]; } void Lee(int st, int ed) { ClearQ(); memset(Distance, 0, sizeof Distance); sort(Chest[st].begin(), Chest[st].end(), cmp); Q.push(Chest[st][0]); Distance[Chest[st][0].first][Chest[st][0].second] = dp[Chest[st][0].first][Chest[st][0].second]; int toAdd = 1; while (Q.size()) { pair<int, int> node = Q.front(); Q.pop(); for (int i = 0; i < 4; ++i) { int xNew = node.first + dir[i][0]; int yNew = node.second + dir[i][1]; if (InBounds(xNew, yNew) and !Distance[xNew][yNew]) { Distance[xNew][yNew] = Distance[node.first][node.second] + 1; for (; toAdd < (int)Chest[st].size() and dp[Chest[st][toAdd].first][Chest[st][toAdd].second] <= Distance[xNew][yNew]; ++toAdd) { Distance[Chest[st][toAdd].first][Chest[st][toAdd].second] = dp[Chest[st][toAdd].first][Chest[st][toAdd].second]; Q.push(Chest[st][toAdd]); } Q.push(make_pair(xNew, yNew)); } } } for (auto it : Chest[ed]) { dp[it.first][it.second] = Distance[it.first][it.second]; } } int main() { ios::sync_with_stdio(false); cin >> n >> m >> p; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { cin >> mat[i][j]; Chest[mat[i][j]].push_back(make_pair(i, j)); } } for (auto it : Chest[1]) { dp[it.first][it.second] = it.first - 1 + it.second - 1; } for (int i = 2; i <= p; ++i) { if (Chest[i].size() * Chest[i - 1].size() <= m * n) { for (auto it2 : Chest[i]) { int currAns = Inf; for (auto it1 : Chest[i - 1]) { currAns = min(currAns, dp[it1.first][it1.second] + abs(it2.first - it1.first) + abs(it2.second - it1.second)); } dp[it2.first][it2.second] = currAns; } } else { Lee(i - 1, i); } } cout << dp[Chest[p][0].first][Chest[p][0].second] << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; struct data { int x, y, val, minVal, rMin; data(int X, int Y) { x = X; y = Y; val = 0; minVal = 1e9; rMin = 1e9; } }; vector<data> a[int(1e5 + 100)]; int Small, n, m, p; bool cmp(data x, data y) { return x.val < y.val; } bool cmp2(data x, data y) { return x.x < y.x; } int dist(data x, data y) { return abs(x.x - y.x) + abs(x.y - y.y); } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); a[x].push_back(data(i, j)); } Small = 1e9; for (int i = 0; i < a[1].size(); i++) { a[1][i].val = a[1][i].x + a[1][i].y - 2; a[1][i].rMin = a[1][i].val; a[1][i].minVal = a[1][i].val; Small = min(Small, a[1][i].val); } sort(a[1].begin(), a[1].end(), cmp); for (int i = 1; i < a[1].size(); i++) a[1][i].minVal = min(a[1][i - 1].minVal, a[1][i].val); for (int i = int(a[1].size()) - 2; i >= 0; i--) a[1][i].rMin = min(a[1][i + 1].rMin, a[1][i].val); int l = max(0, int(a[1].size()) - n - m); int x = a[1].size() - 1; while (a[1][x].val - Small > n + m) { l++; x--; } sort(a[1].begin(), a[1].begin() + int(a[1].size()) - l, cmp2); for (int i = 2; i <= p; i++) { Small = 1e9; for (int j = 0; j < a[i].size(); j++) { int tmp = 1e9; for (int k = 0; k < a[i - 1].size() - l; k++) tmp = min(tmp, dist(a[i][j], a[i - 1][k]) + a[i - 1][k].val); Small = min(Small, tmp); a[i][j].val = tmp; } l = max(0, int(a[i].size()) - n - m); sort(a[i].begin(), a[i].end(), cmp); a[i][0].minVal = a[i][0].val; a[i][a[i].size() - 1].rMin = a[i][a[i].size() - 1].val; int x = a[i].size() - l - 1; while (a[i][x].val - Small > n + m) { l++; x--; } sort(a[i].begin(), a[i].begin() + int(a[i].size()) - l, cmp2); } int ans = Small; cout << ans; }
### Prompt Please provide a Cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct data { int x, y, val, minVal, rMin; data(int X, int Y) { x = X; y = Y; val = 0; minVal = 1e9; rMin = 1e9; } }; vector<data> a[int(1e5 + 100)]; int Small, n, m, p; bool cmp(data x, data y) { return x.val < y.val; } bool cmp2(data x, data y) { return x.x < y.x; } int dist(data x, data y) { return abs(x.x - y.x) + abs(x.y - y.y); } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); a[x].push_back(data(i, j)); } Small = 1e9; for (int i = 0; i < a[1].size(); i++) { a[1][i].val = a[1][i].x + a[1][i].y - 2; a[1][i].rMin = a[1][i].val; a[1][i].minVal = a[1][i].val; Small = min(Small, a[1][i].val); } sort(a[1].begin(), a[1].end(), cmp); for (int i = 1; i < a[1].size(); i++) a[1][i].minVal = min(a[1][i - 1].minVal, a[1][i].val); for (int i = int(a[1].size()) - 2; i >= 0; i--) a[1][i].rMin = min(a[1][i + 1].rMin, a[1][i].val); int l = max(0, int(a[1].size()) - n - m); int x = a[1].size() - 1; while (a[1][x].val - Small > n + m) { l++; x--; } sort(a[1].begin(), a[1].begin() + int(a[1].size()) - l, cmp2); for (int i = 2; i <= p; i++) { Small = 1e9; for (int j = 0; j < a[i].size(); j++) { int tmp = 1e9; for (int k = 0; k < a[i - 1].size() - l; k++) tmp = min(tmp, dist(a[i][j], a[i - 1][k]) + a[i - 1][k].val); Small = min(Small, tmp); a[i][j].val = tmp; } l = max(0, int(a[i].size()) - n - m); sort(a[i].begin(), a[i].end(), cmp); a[i][0].minVal = a[i][0].val; a[i][a[i].size() - 1].rMin = a[i][a[i].size() - 1].val; int x = a[i].size() - l - 1; while (a[i][x].val - Small > n + m) { l++; x--; } sort(a[i].begin(), a[i].begin() + int(a[i].size()) - l, cmp2); } int ans = Small; cout << ans; } ```
#include <bits/stdc++.h> using namespace std; const int N = (int)4e2; const int INF = (int)1e9; int n, m, a[N][N], p; int dyn[N][N], last[N]; vector<pair<int, int> > q[N * N]; int len[N][N]; int main() { cin >> n >> m >> p; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; q[a[i][j]].push_back(make_pair(i, j)); dyn[i][j] = INF; } } for (int i = 0; i < m; ++i) { dyn[0][i] = i; } for (int lvl = 1; lvl <= p; ++lvl) { int x, y; for (auto tmp : q[lvl]) { tie(x, y) = tmp; int ans = INF; for (int row = 0; row < n; ++row) { if (last[row] == lvl - 1) { ans = min(ans, dyn[row][y] + abs(row - x)); } } len[x][y] = ans; } for (auto tmp : q[lvl]) { tie(x, y) = tmp; if (last[x] != lvl) { last[x] = lvl; for (int col = 0; col < m; ++col) { dyn[x][col] = len[x][y] + abs(y - col); } } else { for (int col = 0; col < m; ++col) { dyn[x][col] = min(dyn[x][col], len[x][y] + abs(y - col)); } } } } cout << len[q[p][0].first][q[p][0].second] << '\n'; return 0; }
### Prompt Generate a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = (int)4e2; const int INF = (int)1e9; int n, m, a[N][N], p; int dyn[N][N], last[N]; vector<pair<int, int> > q[N * N]; int len[N][N]; int main() { cin >> n >> m >> p; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; q[a[i][j]].push_back(make_pair(i, j)); dyn[i][j] = INF; } } for (int i = 0; i < m; ++i) { dyn[0][i] = i; } for (int lvl = 1; lvl <= p; ++lvl) { int x, y; for (auto tmp : q[lvl]) { tie(x, y) = tmp; int ans = INF; for (int row = 0; row < n; ++row) { if (last[row] == lvl - 1) { ans = min(ans, dyn[row][y] + abs(row - x)); } } len[x][y] = ans; } for (auto tmp : q[lvl]) { tie(x, y) = tmp; if (last[x] != lvl) { last[x] = lvl; for (int col = 0; col < m; ++col) { dyn[x][col] = len[x][y] + abs(y - col); } } else { for (int col = 0; col < m; ++col) { dyn[x][col] = min(dyn[x][col], len[x][y] + abs(y - col)); } } } } cout << len[q[p][0].first][q[p][0].second] << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; struct s { int x, y, v; bool operator<(const s &a) const { return v < a.v; } }; int n, m, p, x, ans = 1e9; vector<s> dp[309 * 309]; int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> x, dp[x].push_back({i, j, (int)1e9}); dp[0].push_back({0, 0, 0}); for (int i = 0; i < p; i++) { sort(dp[i].begin(), dp[i].end()); for (int j = 0; j < min((int)dp[i].size(), 600); j++) for (auto &k : dp[i + 1]) { k.v = min(k.v, dp[i][j].v + abs(dp[i][j].x - k.x) + abs(dp[i][j].y - k.y)); if (i == p - 1) ans = min(ans, k.v); } } cout << ans << endl; return 0; }
### Prompt Develop a solution in CPP to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct s { int x, y, v; bool operator<(const s &a) const { return v < a.v; } }; int n, m, p, x, ans = 1e9; vector<s> dp[309 * 309]; int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> x, dp[x].push_back({i, j, (int)1e9}); dp[0].push_back({0, 0, 0}); for (int i = 0; i < p; i++) { sort(dp[i].begin(), dp[i].end()); for (int j = 0; j < min((int)dp[i].size(), 600); j++) for (auto &k : dp[i + 1]) { k.v = min(k.v, dp[i][j].v + abs(dp[i][j].x - k.x) + abs(dp[i][j].y - k.y)); if (i == p - 1) ans = min(ans, k.v); } } cout << ans << endl; return 0; } ```
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; const int N = 100010; const int MAX = 2000000000; const int mod = 100000000; const int MOD1 = 1000000007; const int MOD2 = 1000000009; const double EPS = 0.00000001; const long long MOD = 1000000007; const int INF = 1000000010; const double pi = acos(-1.0); struct node { int x, y, z; node() {} node(int _x, int _y, int _z) : x(_x), y(_y), z(_z) {} }; int f[310][310]; vector<node> q[90010]; int main() { int a, i, j, k, n, m, p; scanf("%d%d%d", &n, &m, &p); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { scanf("%d", &a); q[a].push_back(node(i, j, MAX)); } for (i = 0; i < q[1].size(); i++) q[1][i].z = abs(q[1][i].x - 1) + abs(q[1][i].y - 1); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) f[i][j] = MAX; for (i = 1; i < p; i++) { for (j = 0; j < q[i].size(); j++) for (k = 1; k <= m; k++) f[q[i][j].x][k] = min(f[q[i][j].x][k], q[i][j].z + abs(k - q[i][j].y)); for (j = 0; j < q[i + 1].size(); j++) for (k = 1; k <= n; k++) q[i + 1][j].z = min(q[i + 1][j].z, f[k][q[i + 1][j].y] + abs(k - q[i + 1][j].x)); for (j = 0; j < q[i].size(); j++) for (k = 1; k <= m; k++) f[q[i][j].x][k] = MAX; } printf("%d\n", q[p][0].z); return 0; }
### Prompt Please create a solution in Cpp to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; const int N = 100010; const int MAX = 2000000000; const int mod = 100000000; const int MOD1 = 1000000007; const int MOD2 = 1000000009; const double EPS = 0.00000001; const long long MOD = 1000000007; const int INF = 1000000010; const double pi = acos(-1.0); struct node { int x, y, z; node() {} node(int _x, int _y, int _z) : x(_x), y(_y), z(_z) {} }; int f[310][310]; vector<node> q[90010]; int main() { int a, i, j, k, n, m, p; scanf("%d%d%d", &n, &m, &p); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { scanf("%d", &a); q[a].push_back(node(i, j, MAX)); } for (i = 0; i < q[1].size(); i++) q[1][i].z = abs(q[1][i].x - 1) + abs(q[1][i].y - 1); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) f[i][j] = MAX; for (i = 1; i < p; i++) { for (j = 0; j < q[i].size(); j++) for (k = 1; k <= m; k++) f[q[i][j].x][k] = min(f[q[i][j].x][k], q[i][j].z + abs(k - q[i][j].y)); for (j = 0; j < q[i + 1].size(); j++) for (k = 1; k <= n; k++) q[i + 1][j].z = min(q[i + 1][j].z, f[k][q[i + 1][j].y] + abs(k - q[i + 1][j].x)); for (j = 0; j < q[i].size(); j++) for (k = 1; k <= m; k++) f[q[i][j].x][k] = MAX; } printf("%d\n", q[p][0].z); return 0; } ```
#include <bits/stdc++.h> using namespace std; int r, c; const int INF = 1000000009; int g; int ans; int vis[333][333]; int dis[333][333]; vector<pair<int, int> > e[90004]; vector<pair<int, int> > cc[90004]; int p; int main() { scanf("%d %d %d", &r, &c, &p); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { scanf("%d", &g); e[g].push_back(make_pair(i, j)); cc[g].push_back(make_pair(j, i)); dis[i][j] = INF; } } for (int i = 1; i <= p; i++) { sort(e[i].begin(), e[i].end()); sort(cc[i].begin(), cc[i].end()); } queue<pair<pair<int, int>, pair<int, int> > > q; q.push(make_pair(make_pair(0, 0), make_pair(0, 0))); ans = INF; while (!q.empty()) { int cur = q.front().first.first; int ww = q.front().first.second; int xx = q.front().second.first; int yy = q.front().second.second; int d = dis[xx][yy]; if (!cur) { d = 0; } q.pop(); if (cur == p) { ans = min(ans, dis[xx][yy]); continue; } if (ww > dis[xx][yy]) { continue; } int bsr = lower_bound(e[cur + 1].begin(), e[cur + 1].end(), make_pair(xx, -1)) - e[cur + 1].begin(); int bsc = lower_bound(cc[cur + 1].begin(), cc[cur + 1].end(), make_pair(yy, -1)) - cc[cur + 1].begin(); vector<int> allr; if (bsr == e[cur + 1].size()) { bsr--; } if (bsc == cc[cur + 1].size()) { bsc--; } for (int qq = 0; qq < 6; qq++) { if (bsr + qq >= e[cur + 1].size()) { break; } allr.push_back(bsr + qq); } for (int qq = 1; qq < 6; qq++) { if (bsr - qq < 0) { break; } allr.push_back(bsr - qq); } for (int j = 0; j < allr.size(); j++) { int pp = allr[j]; if (pp > -1 && pp < e[cur + 1].size()) { int aa = e[cur + 1][pp].first; int bb = e[cur + 1][pp].second; int dd = abs(xx - aa) + abs(yy - bb) + d; if (dis[aa][bb] > dd) { dis[aa][bb] = dd; q.push(make_pair(make_pair(cur + 1, dis[aa][bb]), make_pair(aa, bb))); } } } allr.clear(); for (int qq = 0; qq < 150; qq++) { if (bsc + qq >= e[cur + 1].size()) { break; } allr.push_back(bsc + qq); } for (int qq = 1; qq < 150; qq++) { if (bsc - qq < 0) { break; } allr.push_back(bsc - qq); } for (int j = 0; j < allr.size(); j++) { int pp = allr[j]; if (pp > -1 && pp < e[cur + 1].size()) { int aa = cc[cur + 1][pp].second; int bb = cc[cur + 1][pp].first; int dd = abs(xx - aa) + abs(yy - bb) + d; if (dis[aa][bb] > dd) { dis[aa][bb] = dd; q.push(make_pair(make_pair(cur + 1, dis[aa][bb]), make_pair(aa, bb))); } } } } printf("%d\n", ans); return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int r, c; const int INF = 1000000009; int g; int ans; int vis[333][333]; int dis[333][333]; vector<pair<int, int> > e[90004]; vector<pair<int, int> > cc[90004]; int p; int main() { scanf("%d %d %d", &r, &c, &p); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { scanf("%d", &g); e[g].push_back(make_pair(i, j)); cc[g].push_back(make_pair(j, i)); dis[i][j] = INF; } } for (int i = 1; i <= p; i++) { sort(e[i].begin(), e[i].end()); sort(cc[i].begin(), cc[i].end()); } queue<pair<pair<int, int>, pair<int, int> > > q; q.push(make_pair(make_pair(0, 0), make_pair(0, 0))); ans = INF; while (!q.empty()) { int cur = q.front().first.first; int ww = q.front().first.second; int xx = q.front().second.first; int yy = q.front().second.second; int d = dis[xx][yy]; if (!cur) { d = 0; } q.pop(); if (cur == p) { ans = min(ans, dis[xx][yy]); continue; } if (ww > dis[xx][yy]) { continue; } int bsr = lower_bound(e[cur + 1].begin(), e[cur + 1].end(), make_pair(xx, -1)) - e[cur + 1].begin(); int bsc = lower_bound(cc[cur + 1].begin(), cc[cur + 1].end(), make_pair(yy, -1)) - cc[cur + 1].begin(); vector<int> allr; if (bsr == e[cur + 1].size()) { bsr--; } if (bsc == cc[cur + 1].size()) { bsc--; } for (int qq = 0; qq < 6; qq++) { if (bsr + qq >= e[cur + 1].size()) { break; } allr.push_back(bsr + qq); } for (int qq = 1; qq < 6; qq++) { if (bsr - qq < 0) { break; } allr.push_back(bsr - qq); } for (int j = 0; j < allr.size(); j++) { int pp = allr[j]; if (pp > -1 && pp < e[cur + 1].size()) { int aa = e[cur + 1][pp].first; int bb = e[cur + 1][pp].second; int dd = abs(xx - aa) + abs(yy - bb) + d; if (dis[aa][bb] > dd) { dis[aa][bb] = dd; q.push(make_pair(make_pair(cur + 1, dis[aa][bb]), make_pair(aa, bb))); } } } allr.clear(); for (int qq = 0; qq < 150; qq++) { if (bsc + qq >= e[cur + 1].size()) { break; } allr.push_back(bsc + qq); } for (int qq = 1; qq < 150; qq++) { if (bsc - qq < 0) { break; } allr.push_back(bsc - qq); } for (int j = 0; j < allr.size(); j++) { int pp = allr[j]; if (pp > -1 && pp < e[cur + 1].size()) { int aa = cc[cur + 1][pp].second; int bb = cc[cur + 1][pp].first; int dd = abs(xx - aa) + abs(yy - bb) + d; if (dis[aa][bb] > dd) { dis[aa][bb] = dd; q.push(make_pair(make_pair(cur + 1, dis[aa][bb]), make_pair(aa, bb))); } } } } printf("%d\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; long long readi() { long long input = 0; char c = ' '; while (c < '-') { c = getchar(); } bool negative = false; if (c == '-') { negative = true; c = getchar(); } while (c >= '0') { input = 10 * input + (c - '0'); c = getchar(); } if (negative) { input = -input; } return input; } void printi(long long output) { if (output == 0) { putchar('0'); return; } if (output < 0) { putchar('-'); output = -output; } int aout[20]; int ilen = 0; while (output) { aout[ilen] = ((output % 10)); output /= 10; ilen++; } for (int i = ilen - 1; i >= 0; i--) { putchar(aout[i] + '0'); } return; } string reads() { string input = ""; char c = ' '; while (c <= ' ') { c = getchar(); } while (c > ' ') { input += c; c = getchar(); } return input; } int sgn(long long x) { if (x < 0) { return -1; } if (x > 0) { return 1; } return 0; } long long randomize(long long x) { return (((1ll << 31) * rand()) + rand()) % x; } const long double PI = 4.0 * atan(1.0); const long double EPS = 0.00000000000000000001; long long normalize(long long x) { return (((x % 1000000007) + 1000000007) % 1000000007); } int N, M, K; vector<pair<int, int> > points[310 * 310]; int grid[310][310]; int dist[310][310]; int temp[310][310]; int dx[4] = {-1, 0, 0, 1}, dy[4] = {0, -1, 1, 0}; queue<pair<int, pair<int, int> > > pq; bool valid(int x, int y) { return 0 <= x && x < N && 0 <= y && y < M; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); srand(time(0)); if (fopen("cf677d.in", "r")) { freopen("cf677d.in", "r", stdin); freopen("cf677d.out", "w", stdout); } cin >> N >> M >> K; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> grid[i][j]; points[grid[i][j]].push_back(make_pair(i, j)); dist[i][j] = 1000000007; if (grid[i][j] == 1) { dist[i][j] = i + j; } } } for (int i = 1; i < K; i++) { if (points[i].size() * points[i + 1].size() > N * M) { for (int j = 0; j < N; j++) { for (int k = 0; k < M; k++) { temp[j][k] = 1000000007; } } for (pair<int, int> u : points[i]) { temp[u.first][u.second] = dist[u.first][u.second]; pq.push(make_pair(temp[u.first][u.second], u)); } while (!pq.empty()) { int d = pq.front().first; pair<int, int> v = pq.front().second; pq.pop(); for (int j = 0; j < 4; j++) { if (valid(v.first + dx[j], v.second + dy[j]) && temp[v.first + dx[j]][v.second + dy[j]] > d + 1) { temp[v.first + dx[j]][v.second + dy[j]] = d + 1; pq.push( make_pair(d + 1, make_pair(v.first + dx[j], v.second + dy[j]))); } } } for (pair<int, int> u : points[i + 1]) { dist[u.first][u.second] = temp[u.first][u.second]; } } else { for (pair<int, int> u : points[i]) { for (pair<int, int> v : points[i + 1]) { dist[v.first][v.second] = min(dist[v.first][v.second], dist[u.first][u.second] + abs(v.first - u.first) + abs(v.second - u.second)); } } } } cout << dist[points[K][0].first][points[K][0].second] << '\n'; return 0; }
### Prompt In cpp, your task is to solve the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long readi() { long long input = 0; char c = ' '; while (c < '-') { c = getchar(); } bool negative = false; if (c == '-') { negative = true; c = getchar(); } while (c >= '0') { input = 10 * input + (c - '0'); c = getchar(); } if (negative) { input = -input; } return input; } void printi(long long output) { if (output == 0) { putchar('0'); return; } if (output < 0) { putchar('-'); output = -output; } int aout[20]; int ilen = 0; while (output) { aout[ilen] = ((output % 10)); output /= 10; ilen++; } for (int i = ilen - 1; i >= 0; i--) { putchar(aout[i] + '0'); } return; } string reads() { string input = ""; char c = ' '; while (c <= ' ') { c = getchar(); } while (c > ' ') { input += c; c = getchar(); } return input; } int sgn(long long x) { if (x < 0) { return -1; } if (x > 0) { return 1; } return 0; } long long randomize(long long x) { return (((1ll << 31) * rand()) + rand()) % x; } const long double PI = 4.0 * atan(1.0); const long double EPS = 0.00000000000000000001; long long normalize(long long x) { return (((x % 1000000007) + 1000000007) % 1000000007); } int N, M, K; vector<pair<int, int> > points[310 * 310]; int grid[310][310]; int dist[310][310]; int temp[310][310]; int dx[4] = {-1, 0, 0, 1}, dy[4] = {0, -1, 1, 0}; queue<pair<int, pair<int, int> > > pq; bool valid(int x, int y) { return 0 <= x && x < N && 0 <= y && y < M; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); srand(time(0)); if (fopen("cf677d.in", "r")) { freopen("cf677d.in", "r", stdin); freopen("cf677d.out", "w", stdout); } cin >> N >> M >> K; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> grid[i][j]; points[grid[i][j]].push_back(make_pair(i, j)); dist[i][j] = 1000000007; if (grid[i][j] == 1) { dist[i][j] = i + j; } } } for (int i = 1; i < K; i++) { if (points[i].size() * points[i + 1].size() > N * M) { for (int j = 0; j < N; j++) { for (int k = 0; k < M; k++) { temp[j][k] = 1000000007; } } for (pair<int, int> u : points[i]) { temp[u.first][u.second] = dist[u.first][u.second]; pq.push(make_pair(temp[u.first][u.second], u)); } while (!pq.empty()) { int d = pq.front().first; pair<int, int> v = pq.front().second; pq.pop(); for (int j = 0; j < 4; j++) { if (valid(v.first + dx[j], v.second + dy[j]) && temp[v.first + dx[j]][v.second + dy[j]] > d + 1) { temp[v.first + dx[j]][v.second + dy[j]] = d + 1; pq.push( make_pair(d + 1, make_pair(v.first + dx[j], v.second + dy[j]))); } } } for (pair<int, int> u : points[i + 1]) { dist[u.first][u.second] = temp[u.first][u.second]; } } else { for (pair<int, int> u : points[i]) { for (pair<int, int> v : points[i + 1]) { dist[v.first][v.second] = min(dist[v.first][v.second], dist[u.first][u.second] + abs(v.first - u.first) + abs(v.second - u.second)); } } } } cout << dist[points[K][0].first][points[K][0].second] << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); int A[500][500]; int D[500][500]; int Dist[310][310]; vector<pair<int, int> > B[250000]; int dist(int x1, int ewrgrg, int x2, int y2) { return abs(x1 - x2) + abs(ewrgrg - y2); } int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int main(int argc, char* argv[]) { int n, m, p; cin >> n >> m >> p; for (int i = (0); i < (n); i++) { for (int j = (0); j < (m); j++) { cin >> A[i][j]; B[A[i][j]].push_back(make_pair(i, j)); D[i][j] = 1000000000; if (A[i][j] == 1) { D[i][j] = dist(0, 0, i, j); } } } for (int j = (1); j < (p); j++) { if (B[j].size() * B[j + 1].size() <= n * m) { for (int k = (0); k < (B[j].size()); k++) { int x = B[j][k].first; int y = B[j][k].second; int d = D[x][y]; for (int i = (0); i < (B[j + 1].size()); i++) { int x1 = B[j + 1][i].first; int ewrgrg = B[j + 1][i].second; D[x1][ewrgrg] = min(D[x1][ewrgrg], d + dist(x, y, x1, ewrgrg)); } } } else { deque<pair<int, int> > q; for (int i = (0); i < (n); i++) { for (int k = (0); k < (m); k++) { Dist[i][k] = 1000000000; } } vector<pair<int, pair<int, int> > > qq; for (int i = (0); i < (B[j].size()); i++) { int x = B[j][i].first; int y = B[j][i].second; qq.push_back(make_pair(D[x][y], make_pair(x, y))); } sort(qq.begin(), qq.end()); int ind = 0; for (; ind < qq.size() && qq[ind].first == qq[0].first; ind++) { int x = qq[ind].second.first; int y = qq[ind].second.second; Dist[x][y] = qq[ind].first; q.push_back(make_pair(x, y)); } while (!q.empty()) { pair<int, int> AA = q.front(); q.pop_front(); int x = AA.first; int y = AA.second; int d = Dist[x][y]; for (; ind < qq.size() && qq[ind].first == d; ind++) { int xx = qq[ind].second.first; int yy = qq[ind].second.second; if (Dist[xx][yy] == 1000000000) { Dist[xx][yy] = d; q.push_front(make_pair(xx, yy)); } } for (int i = (0); i < (4); i++) { int x1 = x + dir[i][0]; int ewrgrg = y + dir[i][1]; if (x1 >= 0 && ewrgrg >= 0 && x1 < n && ewrgrg < m && Dist[x1][ewrgrg] == 1000000000) { Dist[x1][ewrgrg] = d + 1; q.push_back(make_pair(x1, ewrgrg)); } } } for (int i = (0); i < (B[j + 1].size()); i++) { int x = B[j + 1][i].first; int y = B[j + 1][i].second; D[x][y] = Dist[x][y]; } } } cout << D[B[p][0].first][B[p][0].second] << endl; }
### Prompt Create a solution in cpp for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); int A[500][500]; int D[500][500]; int Dist[310][310]; vector<pair<int, int> > B[250000]; int dist(int x1, int ewrgrg, int x2, int y2) { return abs(x1 - x2) + abs(ewrgrg - y2); } int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int main(int argc, char* argv[]) { int n, m, p; cin >> n >> m >> p; for (int i = (0); i < (n); i++) { for (int j = (0); j < (m); j++) { cin >> A[i][j]; B[A[i][j]].push_back(make_pair(i, j)); D[i][j] = 1000000000; if (A[i][j] == 1) { D[i][j] = dist(0, 0, i, j); } } } for (int j = (1); j < (p); j++) { if (B[j].size() * B[j + 1].size() <= n * m) { for (int k = (0); k < (B[j].size()); k++) { int x = B[j][k].first; int y = B[j][k].second; int d = D[x][y]; for (int i = (0); i < (B[j + 1].size()); i++) { int x1 = B[j + 1][i].first; int ewrgrg = B[j + 1][i].second; D[x1][ewrgrg] = min(D[x1][ewrgrg], d + dist(x, y, x1, ewrgrg)); } } } else { deque<pair<int, int> > q; for (int i = (0); i < (n); i++) { for (int k = (0); k < (m); k++) { Dist[i][k] = 1000000000; } } vector<pair<int, pair<int, int> > > qq; for (int i = (0); i < (B[j].size()); i++) { int x = B[j][i].first; int y = B[j][i].second; qq.push_back(make_pair(D[x][y], make_pair(x, y))); } sort(qq.begin(), qq.end()); int ind = 0; for (; ind < qq.size() && qq[ind].first == qq[0].first; ind++) { int x = qq[ind].second.first; int y = qq[ind].second.second; Dist[x][y] = qq[ind].first; q.push_back(make_pair(x, y)); } while (!q.empty()) { pair<int, int> AA = q.front(); q.pop_front(); int x = AA.first; int y = AA.second; int d = Dist[x][y]; for (; ind < qq.size() && qq[ind].first == d; ind++) { int xx = qq[ind].second.first; int yy = qq[ind].second.second; if (Dist[xx][yy] == 1000000000) { Dist[xx][yy] = d; q.push_front(make_pair(xx, yy)); } } for (int i = (0); i < (4); i++) { int x1 = x + dir[i][0]; int ewrgrg = y + dir[i][1]; if (x1 >= 0 && ewrgrg >= 0 && x1 < n && ewrgrg < m && Dist[x1][ewrgrg] == 1000000000) { Dist[x1][ewrgrg] = d + 1; q.push_back(make_pair(x1, ewrgrg)); } } } for (int i = (0); i < (B[j + 1].size()); i++) { int x = B[j + 1][i].first; int y = B[j + 1][i].second; D[x][y] = Dist[x][y]; } } } cout << D[B[p][0].first][B[p][0].second] << endl; } ```
#include <bits/stdc++.h> using namespace std; inline int in() { int32_t x; scanf("%d", &x); return x; } inline string get() { char ch[1001000]; scanf("%s", ch); return ch; } template <class P, class Q> inline P smin(P &a, Q b) { if (b < a) a = b; return a; } template <class P, class Q> inline P smax(P &a, Q b) { if (a < b) a = b; return a; } const long long maxn = 1e6 + 10; const long long base = 29; const long long MAX_LG = 21; const long long mod = 1e9 + 7; const long long INF = 1e18; vector<pair<long long, long long> > where[maxn]; long long a[350][350]; long long dp[350][350]; long long dx[] = {0, 0, -1, 1}; long long dy[] = {1, -1, 0, 0}; bool mark[350][350]; long long res = 1e18; inline long long dis(long long x, long long y, long long x2, long long y2) { return abs(x - x2) + abs(y - y2); } int32_t main() { long long n = in(), m = in(), p = in(); for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { dp[i][j] = INF; a[i][j] = in(); where[a[i][j]].push_back({i, j}); if (a[i][j] == p) { dp[i][j] = 0; if (p == 1) { res = min(res, i + j); } } } } for (long long i = p - 1; i >= 0; i--) { if (max(where[i].size(), where[i + 1].size()) <= sqrt(n * m)) for (long long pt1 = 0; pt1 < where[i].size(); pt1++) { long long x = where[i][pt1].first, y = where[i][pt1].second; for (long long pt2 = 0; pt2 < where[i + 1].size(); pt2++) { long long x2 = where[i + 1][pt2].first, y2 = where[i + 1][pt2].second; dp[x][y] = min(dp[x][y], dp[x2][y2] + dis(x, y, x2, y2)); } if (i == 1) res = min(res, dp[x][y] + dis(0, 0, x, y)); } else { queue<pair<long long, pair<long long, long long> > > q; for (long long x = 0; x < n; x++) for (long long y = 0; y < m; y++) mark[x][y] = 0; vector<pair<long long, pair<long long, long long> > > vc; for (long long pt = 0; pt < where[i + 1].size(); pt++) { long long x = where[i + 1][pt].first, y = where[i + 1][pt].second; vc.push_back({dp[x][y], {x, y}}); } sort(vc.begin(), vc.end()); q.push(vc[0]); long long cur = 1; while (q.size()) { long long x = q.front().second.first, y = q.front().second.second, d = q.front().first; q.pop(); while (cur < vc.size() && vc[cur].first <= d) q.push(vc[cur++]); for (long long p = 0; p < 4; p++) { long long x2 = x + dx[p], y2 = y + dy[p]; if (x2 >= 0 && x2 < n && y2 >= 0 && y2 < m && !mark[x2][y2]) { if (a[x2][y2] == i) dp[x2][y2] = d + 1; mark[x2][y2] = true; q.push({d + 1, {x2, y2}}); } } } for (long long pt = 0; pt < where[i].size(); pt++) { long long x = where[i][pt].first, y = where[i][pt].second; if (i == 1) res = min(res, dp[x][y] + dis(0, 0, x, y)); } } } cout << res << endl; }
### Prompt Generate a cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int in() { int32_t x; scanf("%d", &x); return x; } inline string get() { char ch[1001000]; scanf("%s", ch); return ch; } template <class P, class Q> inline P smin(P &a, Q b) { if (b < a) a = b; return a; } template <class P, class Q> inline P smax(P &a, Q b) { if (a < b) a = b; return a; } const long long maxn = 1e6 + 10; const long long base = 29; const long long MAX_LG = 21; const long long mod = 1e9 + 7; const long long INF = 1e18; vector<pair<long long, long long> > where[maxn]; long long a[350][350]; long long dp[350][350]; long long dx[] = {0, 0, -1, 1}; long long dy[] = {1, -1, 0, 0}; bool mark[350][350]; long long res = 1e18; inline long long dis(long long x, long long y, long long x2, long long y2) { return abs(x - x2) + abs(y - y2); } int32_t main() { long long n = in(), m = in(), p = in(); for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { dp[i][j] = INF; a[i][j] = in(); where[a[i][j]].push_back({i, j}); if (a[i][j] == p) { dp[i][j] = 0; if (p == 1) { res = min(res, i + j); } } } } for (long long i = p - 1; i >= 0; i--) { if (max(where[i].size(), where[i + 1].size()) <= sqrt(n * m)) for (long long pt1 = 0; pt1 < where[i].size(); pt1++) { long long x = where[i][pt1].first, y = where[i][pt1].second; for (long long pt2 = 0; pt2 < where[i + 1].size(); pt2++) { long long x2 = where[i + 1][pt2].first, y2 = where[i + 1][pt2].second; dp[x][y] = min(dp[x][y], dp[x2][y2] + dis(x, y, x2, y2)); } if (i == 1) res = min(res, dp[x][y] + dis(0, 0, x, y)); } else { queue<pair<long long, pair<long long, long long> > > q; for (long long x = 0; x < n; x++) for (long long y = 0; y < m; y++) mark[x][y] = 0; vector<pair<long long, pair<long long, long long> > > vc; for (long long pt = 0; pt < where[i + 1].size(); pt++) { long long x = where[i + 1][pt].first, y = where[i + 1][pt].second; vc.push_back({dp[x][y], {x, y}}); } sort(vc.begin(), vc.end()); q.push(vc[0]); long long cur = 1; while (q.size()) { long long x = q.front().second.first, y = q.front().second.second, d = q.front().first; q.pop(); while (cur < vc.size() && vc[cur].first <= d) q.push(vc[cur++]); for (long long p = 0; p < 4; p++) { long long x2 = x + dx[p], y2 = y + dy[p]; if (x2 >= 0 && x2 < n && y2 >= 0 && y2 < m && !mark[x2][y2]) { if (a[x2][y2] == i) dp[x2][y2] = d + 1; mark[x2][y2] = true; q.push({d + 1, {x2, y2}}); } } } for (long long pt = 0; pt < where[i].size(); pt++) { long long x = where[i][pt].first, y = where[i][pt].second; if (i == 1) res = min(res, dp[x][y] + dis(0, 0, x, y)); } } } cout << res << endl; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p, dp[303][303]; vector<pair<int, int> > G[303 * 303]; int main() { int x, y, z, i, j, k, px, py; scanf("%d%d", &n, &m); scanf("%d", &p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &x); dp[i][j] = 2000000010; if (x == p) px = i, py = j; G[x].push_back(make_pair(i, j)); } } for (int i = 1; i <= p; i++) random_shuffle(G[i].begin(), G[i].end()); for (i = 1; i <= p; i++) { for (j = 0; j < (int)(G[i].size()) && j < 3000; j++) { int nx = G[i][j].first, ny = G[i][j].second; if (i == 1) { dp[nx][ny] = abs(nx - 1) + abs(ny - 1); continue; } for (k = 0; k < (int)(G[i - 1].size()) && k < 3000; k++) { int x = G[i - 1][k].first, y = G[i - 1][k].second; dp[nx][ny] = min(dp[nx][ny], dp[x][y] + abs(nx - x) + abs(ny - y)); } } } printf("%d\n", dp[px][py]); return 0; }
### Prompt Please create a solution in cpp to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, p, dp[303][303]; vector<pair<int, int> > G[303 * 303]; int main() { int x, y, z, i, j, k, px, py; scanf("%d%d", &n, &m); scanf("%d", &p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &x); dp[i][j] = 2000000010; if (x == p) px = i, py = j; G[x].push_back(make_pair(i, j)); } } for (int i = 1; i <= p; i++) random_shuffle(G[i].begin(), G[i].end()); for (i = 1; i <= p; i++) { for (j = 0; j < (int)(G[i].size()) && j < 3000; j++) { int nx = G[i][j].first, ny = G[i][j].second; if (i == 1) { dp[nx][ny] = abs(nx - 1) + abs(ny - 1); continue; } for (k = 0; k < (int)(G[i - 1].size()) && k < 3000; k++) { int x = G[i - 1][k].first, y = G[i - 1][k].second; dp[nx][ny] = min(dp[nx][ny], dp[x][y] + abs(nx - x) + abs(ny - y)); } } } printf("%d\n", dp[px][py]); return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p; int table[301][301]; int dist[301][301]; bool mark[301][301]; vector<vector<pair<int, int> > > vvpii; int CalcDist(pair<int, int> u, pair<int, int> v) { return fabs((u.first) - (v.first)) + fabs((u.second) - (v.second)); } int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; void bfs(vector<pair<int, int> >& from, vector<pair<int, int> >& to, int target) { vector<pair<int, pair<int, int> > > fromW(from.size()); for (int i = 0; i < from.size(); i++) { fromW[i].first = dist[from[i].first][from[i].second]; fromW[i].second.first = from[i].first; fromW[i].second.second = from[i].second; } sort(fromW.begin(), fromW.end()); memset(mark, false, sizeof(mark)); int fromInd = 0; queue<pair<int, pair<int, int> > > Q; Q.push(fromW[fromInd]); mark[fromW[fromInd].second.first][fromW[fromInd].second.second] = true; fromInd++; while (!Q.empty()) { pair<int, pair<int, int> > f = Q.front(); Q.pop(); while (fromInd < fromW.size() && mark[fromW[fromInd].second.first][fromW[fromInd].second.second]) { fromInd++; } while (fromInd < fromW.size() && fromW[fromInd].first <= f.first) { Q.push(fromW[fromInd]); fromInd++; } for (int i = 0; i < 4; i++) { int newI = f.second.first + dir[i][0]; int newJ = f.second.second + dir[i][1]; if (0 <= newI && newI < n && 0 <= newJ && newJ < m && mark[newI][newJ] != true) { Q.push(pair<int, pair<int, int> >(f.first + 1, pair<int, int>(newI, newJ))); mark[newI][newJ] = true; if (table[newI][newJ] == target) dist[newI][newJ] = f.first + 1; } } } } int main() { pair<int, int> target; cin >> n >> m >> p; vvpii = vector<vector<pair<int, int> > >(p + 1, vector<pair<int, int> >()); for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < m; j++) { cin >> table[i][j]; if (table[i][j] == 1) dist[i][j] = i + j; else dist[i][j] = -1; vvpii[table[i][j]].push_back(pair<int, int>(i, j)); if (table[i][j] == p) target = pair<int, int>(i, j); } } for (int i = 2; i <= p; i++) { if (vvpii[i].size() * vvpii[i - 1].size() < n * m) { for (int j = 0; j < vvpii[i].size(); j++) { dist[vvpii[i][j].first][vvpii[i][j].second] = CalcDist(vvpii[i - 1][0], vvpii[i][j]) + dist[vvpii[i - 1][0].first][vvpii[i - 1][0].second]; for (int k = 1; k < vvpii[i - 1].size(); k++) { if (CalcDist(vvpii[i - 1][k], vvpii[i][j]) + dist[vvpii[i - 1][k].first][vvpii[i - 1][k].second] < dist[vvpii[i][j].first][vvpii[i][j].second]) dist[vvpii[i][j].first][vvpii[i][j].second] = CalcDist(vvpii[i - 1][k], vvpii[i][j]) + dist[vvpii[i - 1][k].first][vvpii[i - 1][k].second]; } } } else { bfs(vvpii[i - 1], vvpii[i], i); } } cout << dist[target.first][target.second] << endl; return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, p; int table[301][301]; int dist[301][301]; bool mark[301][301]; vector<vector<pair<int, int> > > vvpii; int CalcDist(pair<int, int> u, pair<int, int> v) { return fabs((u.first) - (v.first)) + fabs((u.second) - (v.second)); } int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; void bfs(vector<pair<int, int> >& from, vector<pair<int, int> >& to, int target) { vector<pair<int, pair<int, int> > > fromW(from.size()); for (int i = 0; i < from.size(); i++) { fromW[i].first = dist[from[i].first][from[i].second]; fromW[i].second.first = from[i].first; fromW[i].second.second = from[i].second; } sort(fromW.begin(), fromW.end()); memset(mark, false, sizeof(mark)); int fromInd = 0; queue<pair<int, pair<int, int> > > Q; Q.push(fromW[fromInd]); mark[fromW[fromInd].second.first][fromW[fromInd].second.second] = true; fromInd++; while (!Q.empty()) { pair<int, pair<int, int> > f = Q.front(); Q.pop(); while (fromInd < fromW.size() && mark[fromW[fromInd].second.first][fromW[fromInd].second.second]) { fromInd++; } while (fromInd < fromW.size() && fromW[fromInd].first <= f.first) { Q.push(fromW[fromInd]); fromInd++; } for (int i = 0; i < 4; i++) { int newI = f.second.first + dir[i][0]; int newJ = f.second.second + dir[i][1]; if (0 <= newI && newI < n && 0 <= newJ && newJ < m && mark[newI][newJ] != true) { Q.push(pair<int, pair<int, int> >(f.first + 1, pair<int, int>(newI, newJ))); mark[newI][newJ] = true; if (table[newI][newJ] == target) dist[newI][newJ] = f.first + 1; } } } } int main() { pair<int, int> target; cin >> n >> m >> p; vvpii = vector<vector<pair<int, int> > >(p + 1, vector<pair<int, int> >()); for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < m; j++) { cin >> table[i][j]; if (table[i][j] == 1) dist[i][j] = i + j; else dist[i][j] = -1; vvpii[table[i][j]].push_back(pair<int, int>(i, j)); if (table[i][j] == p) target = pair<int, int>(i, j); } } for (int i = 2; i <= p; i++) { if (vvpii[i].size() * vvpii[i - 1].size() < n * m) { for (int j = 0; j < vvpii[i].size(); j++) { dist[vvpii[i][j].first][vvpii[i][j].second] = CalcDist(vvpii[i - 1][0], vvpii[i][j]) + dist[vvpii[i - 1][0].first][vvpii[i - 1][0].second]; for (int k = 1; k < vvpii[i - 1].size(); k++) { if (CalcDist(vvpii[i - 1][k], vvpii[i][j]) + dist[vvpii[i - 1][k].first][vvpii[i - 1][k].second] < dist[vvpii[i][j].first][vvpii[i][j].second]) dist[vvpii[i][j].first][vvpii[i][j].second] = CalcDist(vvpii[i - 1][k], vvpii[i][j]) + dist[vvpii[i - 1][k].first][vvpii[i - 1][k].second]; } } } else { bfs(vvpii[i - 1], vvpii[i], i); } } cout << dist[target.first][target.second] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 5; const int nax = 305; int type[nax][nax]; vector<int> col[nax]; int dp[nax][nax]; vector<pair<int, int>> odw[nax * nax]; bool vis[nax]; int n, m, p; void pr() {} int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { scanf("%d", &type[i][j]); if (type[i][j] == 1) dp[i][j] = j + i; else dp[i][j] = inf; odw[type[i][j]].push_back(make_pair(i, j)); } pr(); for (int val = 1; val <= p - 1; ++val) { for (int i = 0; i < max(m, n); ++i) { col[i].clear(); vis[i] = false; } for (pair<int, int> p : odw[val + 1]) { int i = p.first; int j = p.second; col[j].push_back(i); } for (pair<int, int> p : odw[val]) vis[p.first] = true; for (int y = 0; y < n; ++y) if (vis[y]) { int best = inf; for (int x = 0; x < m; ++x) { ++best; if (type[y][x] == val) best = min(best, dp[y][x]); for (int he : col[x]) dp[he][x] = min(dp[he][x], best + abs(he - y)); } best = inf; for (int x = m - 1; x >= 0; --x) { ++best; if (type[y][x] == val) best = min(best, dp[y][x]); for (int he : col[x]) dp[he][x] = min(dp[he][x], best + abs(he - y)); } } pr(); } for (int x = 0; x < m; ++x) for (int y = 0; y < n; ++y) if (type[y][x] == p) printf("%d\n", dp[y][x]); return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 5; const int nax = 305; int type[nax][nax]; vector<int> col[nax]; int dp[nax][nax]; vector<pair<int, int>> odw[nax * nax]; bool vis[nax]; int n, m, p; void pr() {} int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { scanf("%d", &type[i][j]); if (type[i][j] == 1) dp[i][j] = j + i; else dp[i][j] = inf; odw[type[i][j]].push_back(make_pair(i, j)); } pr(); for (int val = 1; val <= p - 1; ++val) { for (int i = 0; i < max(m, n); ++i) { col[i].clear(); vis[i] = false; } for (pair<int, int> p : odw[val + 1]) { int i = p.first; int j = p.second; col[j].push_back(i); } for (pair<int, int> p : odw[val]) vis[p.first] = true; for (int y = 0; y < n; ++y) if (vis[y]) { int best = inf; for (int x = 0; x < m; ++x) { ++best; if (type[y][x] == val) best = min(best, dp[y][x]); for (int he : col[x]) dp[he][x] = min(dp[he][x], best + abs(he - y)); } best = inf; for (int x = m - 1; x >= 0; --x) { ++best; if (type[y][x] == val) best = min(best, dp[y][x]); for (int he : col[x]) dp[he][x] = min(dp[he][x], best + abs(he - y)); } } pr(); } for (int x = 0; x < m; ++x) for (int y = 0; y < n; ++y) if (type[y][x] == p) printf("%d\n", dp[y][x]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const double PI = acos(-1.0); const int inf = 0x3f3f3f3f; template <class T> void read(T& num) { char CH; bool F = false; for (CH = getchar(); CH < '0' || CH > '9'; F = CH == '-', CH = getchar()) ; for (num = 0; CH >= '0' && CH <= '9'; num = num * 10 + CH - '0', CH = getchar()) ; F && (num = -num); } int stk[70], tp; template <class T> inline void print(T p) { if (!p) { puts("0"); return; } while (p) stk[++tp] = p % 10, p /= 10; while (tp) putchar(stk[tp--] + '0'); putchar('\n'); } struct node { int al, ar; int mx; }; struct node1 { int hl, hr; node subt[4000]; } t[4][310 * 4]; void build_sub(int id, int rt, int ll, int rr, int flag) { t[flag][id].subt[rt].al = ll; t[flag][id].subt[rt].ar = rr; t[flag][id].subt[rt].mx = inf; if (ll == rr) { return; } int mid = (ll + rr) >> 1; build_sub(id, rt << 1, ll, mid, flag); build_sub(id, rt << 1 | 1, mid + 1, rr, flag); } void build(int id, int l, int r, int ll, int rr, int flag) { t[flag][id].hl = l; t[flag][id].hr = r; build_sub(id, 1, ll, rr, flag); if (l == r) return; int mid = (l + r) >> 1; build(id << 1, l, mid, ll, rr, flag); build(id << 1 | 1, mid + 1, r, ll, rr, flag); } void add_sub(int id, int rt, int act, int love, int flag) { t[flag][id].subt[rt].mx = min(love, t[flag][id].subt[rt].mx); if (t[flag][id].subt[rt].al == t[flag][id].subt[rt].ar) return; int mid = (t[flag][id].subt[rt].al + t[flag][id].subt[rt].ar) >> 1; if (act <= mid) add_sub(id, rt << 1, act, love, flag); else add_sub(id, rt << 1 | 1, act, love, flag); t[flag][id].subt[rt].mx = min(t[flag][id].subt[rt << 1].mx, t[flag][id].subt[rt << 1 | 1].mx); } void add(int id, int h, int act, int love, int flag) { add_sub(id, 1, act, love, flag); if (t[flag][id].hl == t[flag][id].hr) { return; } int mid = (t[flag][id].hl + t[flag][id].hr) >> 1; if (h <= mid) add(id << 1, h, act, love, flag); else add(id << 1 | 1, h, act, love, flag); } void add_sub1(int id, int rt, int act, int love, int flag) { t[flag][id].subt[rt].mx = love; if (t[flag][id].subt[rt].al == t[flag][id].subt[rt].ar) return; int mid = (t[flag][id].subt[rt].al + t[flag][id].subt[rt].ar) >> 1; if (act <= mid) add_sub1(id, rt << 1, act, love, flag); else add_sub1(id, rt << 1 | 1, act, love, flag); t[flag][id].subt[rt].mx = love; } void add1(int id, int h, int act, int love, int flag) { add_sub1(id, 1, act, love, flag); if (t[flag][id].hl == t[flag][id].hr) { return; } int mid = (t[flag][id].hl + t[flag][id].hr) >> 1; if (h <= mid) add1(id << 1, h, act, love, flag); else add1(id << 1 | 1, h, act, love, flag); } int sear(int id, int rt, int ll, int rr, int flag) { if (t[flag][id].subt[rt].al == ll && t[flag][id].subt[rt].ar == rr) { return t[flag][id].subt[rt].mx; } int mid = (t[flag][id].subt[rt].al + t[flag][id].subt[rt].ar) >> 1; if (rr <= mid) return sear(id, rt << 1, ll, rr, flag); else if (ll > mid) return sear(id, rt << 1 | 1, ll, rr, flag); else return min(sear(id, rt << 1, ll, mid, flag), sear(id, rt << 1 | 1, mid + 1, rr, flag)); } int query(int id, int l, int r, int ll, int rr, int flag) { if (t[flag][id].hl == l && t[flag][id].hr == r) { return sear(id, 1, ll, rr, flag); } int mid = (t[flag][id].hl + t[flag][id].hr) >> 1; if (r <= mid) return query(id << 1, l, r, ll, rr, flag); else if (l > mid) return query(id << 1 | 1, l, r, ll, rr, flag); else return min(query(id << 1, l, mid, ll, rr, flag), query(id << 1 | 1, mid + 1, r, ll, rr, flag)); } struct no { int l, r, dis; }; vector<no> ve[310 * 310]; int a[305][305], le[310 * 310]; int n, m, p; int main() { no x; read(n); read(m); read(p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { read(a[i][j]); x.l = i; x.r = j; x.dis = inf; ve[a[i][j]].push_back(x); } } for (int i = 0; i < 4; i++) build(1, 1, n, 1, m, i); for (int i = 1; i <= p; i++) le[i] = ve[i].size(); for (int i = 0; i < le[1]; i++) { int l = ve[1][i].l, r = ve[1][i].r; ve[1][i].dis = l + r - 2; } for (int i = 2; i <= p; i++) { int len1 = le[i], len2 = le[i - 1]; for (int j = 0; j < len2; j++) { int l = ve[i - 1][j].l, r = ve[i - 1][j].r; add(1, l, r, ve[i - 1][j].dis - l - r, 0); add(1, l, r, ve[i - 1][j].dis - l + r, 1); add(1, l, r, ve[i - 1][j].dis + l - r, 2); add(1, l, r, ve[i - 1][j].dis + l + r, 3); } for (int j = 0; j < len1; j++) { int l = ve[i][j].l, r = ve[i][j].r; ve[i][j].dis = min(ve[i][j].dis, query(1, 1, l, 1, r, 0) + l + r); ve[i][j].dis = min(ve[i][j].dis, query(1, 1, l, r, m, 1) + l - r); ve[i][j].dis = min(ve[i][j].dis, query(1, l, n, 1, r, 2) - l + r); ve[i][j].dis = min(ve[i][j].dis, query(1, l, n, r, m, 3) - l - r); } for (int j = 0; j < len2; j++) { add1(1, ve[i - 1][j].l, ve[i - 1][j].r, inf, 0); add1(1, ve[i - 1][j].l, ve[i - 1][j].r, inf, 1); add1(1, ve[i - 1][j].l, ve[i - 1][j].r, inf, 2); add1(1, ve[i - 1][j].l, ve[i - 1][j].r, inf, 3); } } cout << ve[p][0].dis << endl; return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const double PI = acos(-1.0); const int inf = 0x3f3f3f3f; template <class T> void read(T& num) { char CH; bool F = false; for (CH = getchar(); CH < '0' || CH > '9'; F = CH == '-', CH = getchar()) ; for (num = 0; CH >= '0' && CH <= '9'; num = num * 10 + CH - '0', CH = getchar()) ; F && (num = -num); } int stk[70], tp; template <class T> inline void print(T p) { if (!p) { puts("0"); return; } while (p) stk[++tp] = p % 10, p /= 10; while (tp) putchar(stk[tp--] + '0'); putchar('\n'); } struct node { int al, ar; int mx; }; struct node1 { int hl, hr; node subt[4000]; } t[4][310 * 4]; void build_sub(int id, int rt, int ll, int rr, int flag) { t[flag][id].subt[rt].al = ll; t[flag][id].subt[rt].ar = rr; t[flag][id].subt[rt].mx = inf; if (ll == rr) { return; } int mid = (ll + rr) >> 1; build_sub(id, rt << 1, ll, mid, flag); build_sub(id, rt << 1 | 1, mid + 1, rr, flag); } void build(int id, int l, int r, int ll, int rr, int flag) { t[flag][id].hl = l; t[flag][id].hr = r; build_sub(id, 1, ll, rr, flag); if (l == r) return; int mid = (l + r) >> 1; build(id << 1, l, mid, ll, rr, flag); build(id << 1 | 1, mid + 1, r, ll, rr, flag); } void add_sub(int id, int rt, int act, int love, int flag) { t[flag][id].subt[rt].mx = min(love, t[flag][id].subt[rt].mx); if (t[flag][id].subt[rt].al == t[flag][id].subt[rt].ar) return; int mid = (t[flag][id].subt[rt].al + t[flag][id].subt[rt].ar) >> 1; if (act <= mid) add_sub(id, rt << 1, act, love, flag); else add_sub(id, rt << 1 | 1, act, love, flag); t[flag][id].subt[rt].mx = min(t[flag][id].subt[rt << 1].mx, t[flag][id].subt[rt << 1 | 1].mx); } void add(int id, int h, int act, int love, int flag) { add_sub(id, 1, act, love, flag); if (t[flag][id].hl == t[flag][id].hr) { return; } int mid = (t[flag][id].hl + t[flag][id].hr) >> 1; if (h <= mid) add(id << 1, h, act, love, flag); else add(id << 1 | 1, h, act, love, flag); } void add_sub1(int id, int rt, int act, int love, int flag) { t[flag][id].subt[rt].mx = love; if (t[flag][id].subt[rt].al == t[flag][id].subt[rt].ar) return; int mid = (t[flag][id].subt[rt].al + t[flag][id].subt[rt].ar) >> 1; if (act <= mid) add_sub1(id, rt << 1, act, love, flag); else add_sub1(id, rt << 1 | 1, act, love, flag); t[flag][id].subt[rt].mx = love; } void add1(int id, int h, int act, int love, int flag) { add_sub1(id, 1, act, love, flag); if (t[flag][id].hl == t[flag][id].hr) { return; } int mid = (t[flag][id].hl + t[flag][id].hr) >> 1; if (h <= mid) add1(id << 1, h, act, love, flag); else add1(id << 1 | 1, h, act, love, flag); } int sear(int id, int rt, int ll, int rr, int flag) { if (t[flag][id].subt[rt].al == ll && t[flag][id].subt[rt].ar == rr) { return t[flag][id].subt[rt].mx; } int mid = (t[flag][id].subt[rt].al + t[flag][id].subt[rt].ar) >> 1; if (rr <= mid) return sear(id, rt << 1, ll, rr, flag); else if (ll > mid) return sear(id, rt << 1 | 1, ll, rr, flag); else return min(sear(id, rt << 1, ll, mid, flag), sear(id, rt << 1 | 1, mid + 1, rr, flag)); } int query(int id, int l, int r, int ll, int rr, int flag) { if (t[flag][id].hl == l && t[flag][id].hr == r) { return sear(id, 1, ll, rr, flag); } int mid = (t[flag][id].hl + t[flag][id].hr) >> 1; if (r <= mid) return query(id << 1, l, r, ll, rr, flag); else if (l > mid) return query(id << 1 | 1, l, r, ll, rr, flag); else return min(query(id << 1, l, mid, ll, rr, flag), query(id << 1 | 1, mid + 1, r, ll, rr, flag)); } struct no { int l, r, dis; }; vector<no> ve[310 * 310]; int a[305][305], le[310 * 310]; int n, m, p; int main() { no x; read(n); read(m); read(p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { read(a[i][j]); x.l = i; x.r = j; x.dis = inf; ve[a[i][j]].push_back(x); } } for (int i = 0; i < 4; i++) build(1, 1, n, 1, m, i); for (int i = 1; i <= p; i++) le[i] = ve[i].size(); for (int i = 0; i < le[1]; i++) { int l = ve[1][i].l, r = ve[1][i].r; ve[1][i].dis = l + r - 2; } for (int i = 2; i <= p; i++) { int len1 = le[i], len2 = le[i - 1]; for (int j = 0; j < len2; j++) { int l = ve[i - 1][j].l, r = ve[i - 1][j].r; add(1, l, r, ve[i - 1][j].dis - l - r, 0); add(1, l, r, ve[i - 1][j].dis - l + r, 1); add(1, l, r, ve[i - 1][j].dis + l - r, 2); add(1, l, r, ve[i - 1][j].dis + l + r, 3); } for (int j = 0; j < len1; j++) { int l = ve[i][j].l, r = ve[i][j].r; ve[i][j].dis = min(ve[i][j].dis, query(1, 1, l, 1, r, 0) + l + r); ve[i][j].dis = min(ve[i][j].dis, query(1, 1, l, r, m, 1) + l - r); ve[i][j].dis = min(ve[i][j].dis, query(1, l, n, 1, r, 2) - l + r); ve[i][j].dis = min(ve[i][j].dis, query(1, l, n, r, m, 3) - l - r); } for (int j = 0; j < len2; j++) { add1(1, ve[i - 1][j].l, ve[i - 1][j].r, inf, 0); add1(1, ve[i - 1][j].l, ve[i - 1][j].r, inf, 1); add1(1, ve[i - 1][j].l, ve[i - 1][j].r, inf, 2); add1(1, ve[i - 1][j].l, ve[i - 1][j].r, inf, 3); } } cout << ve[p][0].dis << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; int dR[] = {-1, 0, 0, +1}; int dC[] = {0, -1, +1, 0}; int n, m, p, x, grid[303][303], dp[303][303], vis[303][303]; vector<pair<int, int> > a[300 * 300 + 3]; void brute(int x) { for (int i = 0; i < a[x - 1].size(); i++) { pair<int, int> u = a[x - 1][i]; for (int j = 0; j < a[x].size(); j++) { pair<int, int> v = a[x][j]; dp[v.first][v.second] = min(dp[v.first][v.second], dp[u.first][u.second] + abs(v.first - u.first) + abs(v.second - u.second)); } } } bool cmp(pair<int, int> a, pair<int, int> b) { return dp[a.first][a.second] < dp[b.first][b.second]; } void bfs(int x) { memset(vis, -1, sizeof vis); queue<pair<int, int> > q; vector<pair<int, int> > temp; for (int i = 0; i < a[x - 1].size(); i++) { pair<int, int> u = a[x - 1][i]; temp.push_back(u); vis[u.first][u.second] = dp[u.first][u.second]; } sort(temp.begin(), temp.end(), cmp); int in = 0; vis[temp[in].first][temp[in].second] = dp[temp[in].first][temp[in].second]; q.push(temp[in++]); while (!q.empty()) { pair<int, int> U = q.front(); int ur = U.first, uc = U.second; q.pop(); while (in < temp.size() && dp[temp[in].first][temp[in].second] <= vis[ur][uc] + 1) { q.push(temp[in++]); } for (int i = 0; i < 4; i++) { int vr = ur + dR[i]; int vc = uc + dC[i]; if (vr < 0 || vr == n || vc < 0 || vc == m || vis[vr][vc] != -1 || grid[vr][vc] == x - 1) continue; vis[vr][vc] = vis[ur][uc] + 1; q.push(pair<int, int>(vr, vc)); } } for (int i = 0; i < a[x].size(); i++) { pair<int, int> u = a[x][i]; dp[u.first][u.second] = min(dp[u.first][u.second], vis[u.first][u.second]); } } int main() { scanf("%d %d %d", &n, &m, &p); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &x); grid[i][j] = x; a[x].push_back(pair<int, int>(i, j)); } } for (int i = 0; i <= 300; i++) for (int j = 0; j <= 300; j++) dp[i][j] = 1000000000; for (int i = 0; i < a[1].size(); i++) { dp[a[1][i].first][a[1][i].second] = a[1][i].first + a[1][i].second; } for (int c = 2; c <= p; c++) { if (a[c - 1].size() * a[c].size() <= n * m) brute(c); else bfs(c); } printf("%d\n", dp[a[p][0].first][a[p][0].second]); }
### Prompt Create a solution in cpp for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int dR[] = {-1, 0, 0, +1}; int dC[] = {0, -1, +1, 0}; int n, m, p, x, grid[303][303], dp[303][303], vis[303][303]; vector<pair<int, int> > a[300 * 300 + 3]; void brute(int x) { for (int i = 0; i < a[x - 1].size(); i++) { pair<int, int> u = a[x - 1][i]; for (int j = 0; j < a[x].size(); j++) { pair<int, int> v = a[x][j]; dp[v.first][v.second] = min(dp[v.first][v.second], dp[u.first][u.second] + abs(v.first - u.first) + abs(v.second - u.second)); } } } bool cmp(pair<int, int> a, pair<int, int> b) { return dp[a.first][a.second] < dp[b.first][b.second]; } void bfs(int x) { memset(vis, -1, sizeof vis); queue<pair<int, int> > q; vector<pair<int, int> > temp; for (int i = 0; i < a[x - 1].size(); i++) { pair<int, int> u = a[x - 1][i]; temp.push_back(u); vis[u.first][u.second] = dp[u.first][u.second]; } sort(temp.begin(), temp.end(), cmp); int in = 0; vis[temp[in].first][temp[in].second] = dp[temp[in].first][temp[in].second]; q.push(temp[in++]); while (!q.empty()) { pair<int, int> U = q.front(); int ur = U.first, uc = U.second; q.pop(); while (in < temp.size() && dp[temp[in].first][temp[in].second] <= vis[ur][uc] + 1) { q.push(temp[in++]); } for (int i = 0; i < 4; i++) { int vr = ur + dR[i]; int vc = uc + dC[i]; if (vr < 0 || vr == n || vc < 0 || vc == m || vis[vr][vc] != -1 || grid[vr][vc] == x - 1) continue; vis[vr][vc] = vis[ur][uc] + 1; q.push(pair<int, int>(vr, vc)); } } for (int i = 0; i < a[x].size(); i++) { pair<int, int> u = a[x][i]; dp[u.first][u.second] = min(dp[u.first][u.second], vis[u.first][u.second]); } } int main() { scanf("%d %d %d", &n, &m, &p); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &x); grid[i][j] = x; a[x].push_back(pair<int, int>(i, j)); } } for (int i = 0; i <= 300; i++) for (int j = 0; j <= 300; j++) dp[i][j] = 1000000000; for (int i = 0; i < a[1].size(); i++) { dp[a[1][i].first][a[1][i].second] = a[1][i].first + a[1][i].second; } for (int c = 2; c <= p; c++) { if (a[c - 1].size() * a[c].size() <= n * m) brute(c); else bfs(c); } printf("%d\n", dp[a[p][0].first][a[p][0].second]); } ```
#include <bits/stdc++.h> using namespace std; vector<pair<int, pair<int, int> > > v[300 * 300 + 1]; int main() { int n, m, p, x; cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &x); v[x].push_back({(int)1e9, {i, j}}); } v[0].push_back({0, {1, 1}}); for (int i = 1; i <= p; i++) { sort(v[i - 1].begin(), v[i - 1].end()); for (int k = 0; k < v[i].size(); k++) { for (int j = 0; j < min((int)v[i - 1].size(), 2000); j++) v[i][k].first = min(v[i][k].first, v[i - 1][j].first + abs(v[i - 1][j].second.first - v[i][k].second.first) + abs(v[i - 1][j].second.second - v[i][k].second.second)); } } cout << v[p][0].first; }
### Prompt Please provide a cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<pair<int, pair<int, int> > > v[300 * 300 + 1]; int main() { int n, m, p, x; cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &x); v[x].push_back({(int)1e9, {i, j}}); } v[0].push_back({0, {1, 1}}); for (int i = 1; i <= p; i++) { sort(v[i - 1].begin(), v[i - 1].end()); for (int k = 0; k < v[i].size(); k++) { for (int j = 0; j < min((int)v[i - 1].size(), 2000); j++) v[i][k].first = min(v[i][k].first, v[i - 1][j].first + abs(v[i - 1][j].second.first - v[i][k].second.first) + abs(v[i - 1][j].second.second - v[i][k].second.second)); } } cout << v[p][0].first; } ```
#include <bits/stdc++.h> using namespace std; template <class T> void read(T& num) { char CH; bool F = false; for (CH = getchar(); CH < '0' || CH > '9'; F = CH == '-', CH = getchar()) ; for (num = 0; CH >= '0' && CH <= '9'; num = num * 10 + CH - '0', CH = getchar()) ; F && (num = -num); } int stk[70], tp; template <class T> inline void print(T p) { if (!p) { puts("0"); return; } while (p) stk[++tp] = p % 10, p /= 10; while (tp) putchar(stk[tp--] + '0'); putchar('\n'); } const long long mod = 1e9 + 7; const double PI = acos(-1.0); const long long inf = 1e14; const int N = 1e5 + 15; struct node { int l, r, dis; }; vector<node> ve[N]; int cmp(node x, node y) { return x.dis < y.dis; } long long dp[305][305]; int a[305][305], le[N]; int n, m, p; int main() { node x; read(n); read(m); read(p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) dp[i][j] = inf; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { read(a[i][j]); x.l = i; x.r = j; ve[a[i][j]].push_back(x); } } for (int i = 1; i <= p; i++) { le[i] = ve[i].size(); } for (int i = 0; i < le[1]; i++) { int l = ve[1][i].l, r = ve[1][i].r; dp[l][r] = l + r - 2; ve[1][i].dis = dp[l][r]; } sort(ve[1].begin(), ve[1].end(), cmp); for (int i = 2; i <= p; i++) { int len1 = le[i], len2 = le[i - 1]; for (int j = 0; j < le[i]; j++) { int l = ve[i][j].l, r = ve[i][j].r; for (int k = 0; k < min(le[i - 1], 4000); k++) { int fl = ve[i - 1][k].l, fr = ve[i - 1][k].r; if (dp[fl][fr] >= dp[l][r]) break; dp[l][r] = min(dp[l][r], dp[fl][fr] + abs(fl - l) + abs(fr - r)); } ve[i][j].dis = dp[l][r]; } sort(ve[i].begin(), ve[i].end(), cmp); } int l = ve[p][0].l, r = ve[p][0].r; print(dp[l][r]); return 0; }
### Prompt Please create a solution in CPP to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class T> void read(T& num) { char CH; bool F = false; for (CH = getchar(); CH < '0' || CH > '9'; F = CH == '-', CH = getchar()) ; for (num = 0; CH >= '0' && CH <= '9'; num = num * 10 + CH - '0', CH = getchar()) ; F && (num = -num); } int stk[70], tp; template <class T> inline void print(T p) { if (!p) { puts("0"); return; } while (p) stk[++tp] = p % 10, p /= 10; while (tp) putchar(stk[tp--] + '0'); putchar('\n'); } const long long mod = 1e9 + 7; const double PI = acos(-1.0); const long long inf = 1e14; const int N = 1e5 + 15; struct node { int l, r, dis; }; vector<node> ve[N]; int cmp(node x, node y) { return x.dis < y.dis; } long long dp[305][305]; int a[305][305], le[N]; int n, m, p; int main() { node x; read(n); read(m); read(p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) dp[i][j] = inf; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { read(a[i][j]); x.l = i; x.r = j; ve[a[i][j]].push_back(x); } } for (int i = 1; i <= p; i++) { le[i] = ve[i].size(); } for (int i = 0; i < le[1]; i++) { int l = ve[1][i].l, r = ve[1][i].r; dp[l][r] = l + r - 2; ve[1][i].dis = dp[l][r]; } sort(ve[1].begin(), ve[1].end(), cmp); for (int i = 2; i <= p; i++) { int len1 = le[i], len2 = le[i - 1]; for (int j = 0; j < le[i]; j++) { int l = ve[i][j].l, r = ve[i][j].r; for (int k = 0; k < min(le[i - 1], 4000); k++) { int fl = ve[i - 1][k].l, fr = ve[i - 1][k].r; if (dp[fl][fr] >= dp[l][r]) break; dp[l][r] = min(dp[l][r], dp[fl][fr] + abs(fl - l) + abs(fr - r)); } ve[i][j].dis = dp[l][r]; } sort(ve[i].begin(), ve[i].end(), cmp); } int l = ve[p][0].l, r = ve[p][0].r; print(dp[l][r]); return 0; } ```
#include <bits/stdc++.h> using namespace std; int i, j, n, h, x, y, glob, k, m, p, fx, fy; int a[505][505], dp[505][505], d[505][505], t[4][2005][2005]; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; vector<pair<int, int> > g[250505]; vector<pair<int, pair<int, int> > > lst, bfs; int Abs(int x) { return x > 0 ? x : -x; } int find_dist(int x1, int y1, int x2, int y2) { return Abs(x1 - x2) + Abs(y1 - y2); } bool in_range(int x, int y) { return (x >= 0 && x < y); } int get(int lx, int rx, int ly, int ry) { rx++; ry++; int res = 1000000007; int l = ly, r = ry; for (lx += 512, rx += 512; lx < rx; lx >>= 1, rx >>= 1) { if (rx & 1) { ly = l; ry = r; rx--; for (ly += 512, ry += 512; ly < ry; ly >>= 1, ry >>= 1) { if (ly & 1) { res = min(res, t[glob][rx][ly]); ly++; } if (ry & 1) { --ry; res = min(res, t[glob][rx][ry]); } } } if (lx & 1) { ly = l; ry = r; for (ly += 512, ry += 512; ly < ry; ly >>= 1, ry >>= 1) { if (ly & 1) { res = min(res, t[glob][lx][ly]); ly++; } if (ry & 1) { --ry; res = min(res, t[glob][lx][ry]); } } lx++; } } return res; } void update(int x, int y, int val) { int tmp = y; t[glob][x + 512][tmp + 512] = val; for (x += 512; x > 1; x >>= 1) { y = tmp; for (y += 512; y > 1; y >>= 1) { t[glob][x][y >> 1] = min(t[glob][x][y], t[glob][x][y ^ 1]); t[glob][x >> 1][y] = min(t[glob][x][y], t[glob][x ^ 1][y]); } t[glob][x >> 1][y] = min(t[glob][x][y], t[glob][x ^ 1][y]); } } int main() { cin >> n >> m >> p; for (i = 0; i < n; i++) for (j = 0; j < m; j++) dp[i][j] = 1000000007; for (i = 0; i < n; i++) for (j = 0; j < m; j++) { scanf("%d", &a[i][j]); g[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) dp[i][j] = i + j; if (a[i][j] == p) fx = i, fy = j; } for (i = 0; i <= 512 * 2; i++) for (j = 0; j <= 512 * 2; j++) for (k = 0; k < 4; k++) t[k][i][j] = 1000000007; for (i = 2; i <= p; i++) { int last_sz = g[i - 1].size(); for (j = 0; j < last_sz; j++) { int x = g[i - 1][j].first; int y = g[i - 1][j].second; glob = 0; update(x, y, dp[x][y] - x - y); glob = 1; update(x, y, dp[x][y] - x + y); glob = 2; update(x, y, dp[x][y] + x - y); glob = 3; update(x, y, dp[x][y] + x + y); } int cur_sz = g[i].size(); for (j = 0; j < cur_sz; j++) { int x = g[i][j].first; int y = g[i][j].second; glob = 0; dp[x][y] = min(dp[x][y], get(0, x, 0, y) + x + y); glob = 1; dp[x][y] = min(dp[x][y], get(0, x, y, m - 1) + x - y); glob = 2; dp[x][y] = min(dp[x][y], get(x, n - 1, 0, y) - x + y); glob = 3; dp[x][y] = min(dp[x][y], get(x, n - 1, y, m - 1) - x - y); } for (j = 0; j < last_sz; j++) { int x = g[i - 1][j].first; int y = g[i - 1][j].second; glob = 0; update(x, y, 1000000007); glob = 1; update(x, y, 1000000007); glob = 2; update(x, y, 1000000007); glob = 3; update(x, y, 1000000007); } } cout << dp[fx][fy] << endl; return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int i, j, n, h, x, y, glob, k, m, p, fx, fy; int a[505][505], dp[505][505], d[505][505], t[4][2005][2005]; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; vector<pair<int, int> > g[250505]; vector<pair<int, pair<int, int> > > lst, bfs; int Abs(int x) { return x > 0 ? x : -x; } int find_dist(int x1, int y1, int x2, int y2) { return Abs(x1 - x2) + Abs(y1 - y2); } bool in_range(int x, int y) { return (x >= 0 && x < y); } int get(int lx, int rx, int ly, int ry) { rx++; ry++; int res = 1000000007; int l = ly, r = ry; for (lx += 512, rx += 512; lx < rx; lx >>= 1, rx >>= 1) { if (rx & 1) { ly = l; ry = r; rx--; for (ly += 512, ry += 512; ly < ry; ly >>= 1, ry >>= 1) { if (ly & 1) { res = min(res, t[glob][rx][ly]); ly++; } if (ry & 1) { --ry; res = min(res, t[glob][rx][ry]); } } } if (lx & 1) { ly = l; ry = r; for (ly += 512, ry += 512; ly < ry; ly >>= 1, ry >>= 1) { if (ly & 1) { res = min(res, t[glob][lx][ly]); ly++; } if (ry & 1) { --ry; res = min(res, t[glob][lx][ry]); } } lx++; } } return res; } void update(int x, int y, int val) { int tmp = y; t[glob][x + 512][tmp + 512] = val; for (x += 512; x > 1; x >>= 1) { y = tmp; for (y += 512; y > 1; y >>= 1) { t[glob][x][y >> 1] = min(t[glob][x][y], t[glob][x][y ^ 1]); t[glob][x >> 1][y] = min(t[glob][x][y], t[glob][x ^ 1][y]); } t[glob][x >> 1][y] = min(t[glob][x][y], t[glob][x ^ 1][y]); } } int main() { cin >> n >> m >> p; for (i = 0; i < n; i++) for (j = 0; j < m; j++) dp[i][j] = 1000000007; for (i = 0; i < n; i++) for (j = 0; j < m; j++) { scanf("%d", &a[i][j]); g[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) dp[i][j] = i + j; if (a[i][j] == p) fx = i, fy = j; } for (i = 0; i <= 512 * 2; i++) for (j = 0; j <= 512 * 2; j++) for (k = 0; k < 4; k++) t[k][i][j] = 1000000007; for (i = 2; i <= p; i++) { int last_sz = g[i - 1].size(); for (j = 0; j < last_sz; j++) { int x = g[i - 1][j].first; int y = g[i - 1][j].second; glob = 0; update(x, y, dp[x][y] - x - y); glob = 1; update(x, y, dp[x][y] - x + y); glob = 2; update(x, y, dp[x][y] + x - y); glob = 3; update(x, y, dp[x][y] + x + y); } int cur_sz = g[i].size(); for (j = 0; j < cur_sz; j++) { int x = g[i][j].first; int y = g[i][j].second; glob = 0; dp[x][y] = min(dp[x][y], get(0, x, 0, y) + x + y); glob = 1; dp[x][y] = min(dp[x][y], get(0, x, y, m - 1) + x - y); glob = 2; dp[x][y] = min(dp[x][y], get(x, n - 1, 0, y) - x + y); glob = 3; dp[x][y] = min(dp[x][y], get(x, n - 1, y, m - 1) - x - y); } for (j = 0; j < last_sz; j++) { int x = g[i - 1][j].first; int y = g[i - 1][j].second; glob = 0; update(x, y, 1000000007); glob = 1; update(x, y, 1000000007); glob = 2; update(x, y, 1000000007); glob = 3; update(x, y, 1000000007); } } cout << dp[fx][fy] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1 + 300 + 5; const int MAX_M = 1 + 300 + 5; const int MAX_P = MAX_N * MAX_M; const int MAX_INF = 0x3fffffff; const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, 1, -1}; const int dSize = 4; int a[MAX_N][MAX_M]; int dmin[MAX_N][MAX_M]; int N, M, P; vector<pair<int, int> > vec[MAX_P]; bool marked[MAX_N][MAX_M]; int newD[MAX_N][MAX_M]; set<pair<int, pair<int, int> > > Set; void readData() { scanf("%d%d%d", &N, &M, &P); for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { scanf("%d", &a[i][j]); vec[a[i][j]].push_back(make_pair(i, j)); dmin[i][j] = MAX_INF; } } vec[0].push_back(make_pair(1, 1)); for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { if (a[i][j] == 1) { dmin[i][j] = i + j - 2; } } } } bool inTheMatrix(int x, int y) { return (1 <= x && x <= N && 1 <= y && y <= M); } void Reset() { Set.clear(); for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { marked[i][j] = false; newD[i][j] = MAX_INF; } } } void solveLevel(int level) { if ((int)vec[level].size() * vec[level + 1].size() <= 3000000) { for (vector<pair<int, int> >::iterator it1 = vec[level].begin(); it1 != vec[level].end(); ++it1) { for (vector<pair<int, int> >::iterator it2 = vec[level + 1].begin(); it2 != vec[level + 1].end(); ++it2) { dmin[it2->first][it2->second] = min( dmin[it2->first][it2->second], dmin[it1->first][it1->second] + (int)abs(it1->first - it2->first) + (int)abs(it1->second - it2->second)); } } return; } Reset(); for (vector<pair<int, int> >::iterator it = vec[level].begin(); it != vec[level].end(); it++) { Set.insert(make_pair(dmin[it->first][it->second], make_pair(it->first, it->second))); } int RAMASE = N * M; while (!Set.empty() && RAMASE > 0) { set<pair<int, pair<int, int> > >::iterator it = Set.begin(); int currentDist = it->first; int x = it->second.first; int y = it->second.second; Set.erase(it); if (marked[x][y]) { continue; } else { marked[x][y] = true; RAMASE--; } if (a[x][y] == level + 1) { dmin[x][y] = currentDist; } for (int i = 0; i < dSize; i++) { int newX = x + dx[i]; int newY = y + dy[i]; if (inTheMatrix(newX, newY) && !marked[newX][newY]) { if (newD[newX][newY] > currentDist + 1) { Set.insert(make_pair(currentDist + 1, make_pair(newX, newY))); newD[newX][newY] = currentDist + 1; } } } } } void writeData() { for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { if (a[i][j] == P) { printf("%d", dmin[i][j]); return; } } } } int main() { readData(); for (int i = 1; i < P; i++) { solveLevel(i); } writeData(); return 0; }
### Prompt In Cpp, your task is to solve the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAX_N = 1 + 300 + 5; const int MAX_M = 1 + 300 + 5; const int MAX_P = MAX_N * MAX_M; const int MAX_INF = 0x3fffffff; const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, 1, -1}; const int dSize = 4; int a[MAX_N][MAX_M]; int dmin[MAX_N][MAX_M]; int N, M, P; vector<pair<int, int> > vec[MAX_P]; bool marked[MAX_N][MAX_M]; int newD[MAX_N][MAX_M]; set<pair<int, pair<int, int> > > Set; void readData() { scanf("%d%d%d", &N, &M, &P); for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { scanf("%d", &a[i][j]); vec[a[i][j]].push_back(make_pair(i, j)); dmin[i][j] = MAX_INF; } } vec[0].push_back(make_pair(1, 1)); for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { if (a[i][j] == 1) { dmin[i][j] = i + j - 2; } } } } bool inTheMatrix(int x, int y) { return (1 <= x && x <= N && 1 <= y && y <= M); } void Reset() { Set.clear(); for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { marked[i][j] = false; newD[i][j] = MAX_INF; } } } void solveLevel(int level) { if ((int)vec[level].size() * vec[level + 1].size() <= 3000000) { for (vector<pair<int, int> >::iterator it1 = vec[level].begin(); it1 != vec[level].end(); ++it1) { for (vector<pair<int, int> >::iterator it2 = vec[level + 1].begin(); it2 != vec[level + 1].end(); ++it2) { dmin[it2->first][it2->second] = min( dmin[it2->first][it2->second], dmin[it1->first][it1->second] + (int)abs(it1->first - it2->first) + (int)abs(it1->second - it2->second)); } } return; } Reset(); for (vector<pair<int, int> >::iterator it = vec[level].begin(); it != vec[level].end(); it++) { Set.insert(make_pair(dmin[it->first][it->second], make_pair(it->first, it->second))); } int RAMASE = N * M; while (!Set.empty() && RAMASE > 0) { set<pair<int, pair<int, int> > >::iterator it = Set.begin(); int currentDist = it->first; int x = it->second.first; int y = it->second.second; Set.erase(it); if (marked[x][y]) { continue; } else { marked[x][y] = true; RAMASE--; } if (a[x][y] == level + 1) { dmin[x][y] = currentDist; } for (int i = 0; i < dSize; i++) { int newX = x + dx[i]; int newY = y + dy[i]; if (inTheMatrix(newX, newY) && !marked[newX][newY]) { if (newD[newX][newY] > currentDist + 1) { Set.insert(make_pair(currentDist + 1, make_pair(newX, newY))); newD[newX][newY] = currentDist + 1; } } } } } void writeData() { for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { if (a[i][j] == P) { printf("%d", dmin[i][j]); return; } } } } int main() { readData(); for (int i = 1; i < P; i++) { solveLevel(i); } writeData(); return 0; } ```
#include <bits/stdc++.h> using namespace std; void bad(string mes = "Impossible") { cout << mes; exit(0); } template <typename... T> void shit(T&... x) {} template <typename... T> void dec(T&... x) { shit(--x...); } template <typename... T> void inc(T&... x) { shit(++x...); } template <typename T> string bin(T x, int st = 2) { string ans = ""; while (x > 0) { ans += char('0' + x % st); x /= st; } reverse(ans.begin(), ans.end()); return ans.empty() ? "0" : ans; } template <typename T> T dcm(string& second) { T x = 0; for (int i = 0; i < second.size(); i++) { x = (x * 2) + (second[i] == '1'); } return x; } template <typename T> T input() { T ans = 0, m = 1; char c = ' '; while (c == ' ' || c == '\n') c = getchar(); if (c == '-') m = -1, c = getchar(); while (c >= '0' && c <= '9') { ans = ans * 10 + int(c - '0'), c = getchar(); } return ans * m; } const int inf = 1e9; const double eps = 1e-9; const int maxn = 3e2 + 10, base = 1e9 + 7; const int sigm = 26; const long long llinf = 1e18; template <typename T> T binpow(T n, T second) { if (second <= 0) return 1LL; if (second % 2 == 0) { T b = binpow(n, second / 2); return (1LL * b * b) % base; } else { return (1LL * binpow(n, second - 1) * n) % base; } } vector<pair<int, int> > thisColor[maxn * maxn]; int dp[maxn][maxn], dp2[maxn][maxn]; int a[maxn][maxn]; int dist(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } int getDp(const pair<int, int>& kek) { return dp[kek.first][kek.second]; } int getDp2(const pair<int, int>& kek) { return dp2[kek.first][kek.second]; } bool cmp(const pair<int, int>& a, const pair<int, int>& b) { return getDp(a) < getDp(b); } int px[4] = {1, 0, -1, 0}; int py[4] = {0, 1, 0, -1}; int main() { memset(dp, 63, sizeof(dp)); int n, m, p; scanf("%d %d %d", &n, &m, &p); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) dp[i][j] = i + j; thisColor[a[i][j]].push_back(make_pair(i, j)); } int block = (n + m) / 2; for (int color = 2; color <= p; color++) { if (thisColor[color].size() >= block || thisColor[color - 1].size() >= block) { deque<pair<int, int> > q, waitingShit; vector<pair<int, int> > tmp; for (int i = 0; i < thisColor[color - 1].size(); i++) tmp.push_back(thisColor[color - 1][i]); sort(tmp.begin(), tmp.end(), cmp); memset(dp2, 63, sizeof(dp2)); for (int i = 0; i < tmp.size(); i++) waitingShit.push_back(tmp[i]); while (!(q.empty() && waitingShit.empty())) { while (q.empty() || ((waitingShit.size()) && getDp(waitingShit.front()) <= getDp2(q.back()))) { if (q.empty() && waitingShit.empty()) break; pair<int, int> newComer = waitingShit.front(); if (dp2[newComer.first][newComer.second] > getDp(newComer)) { q.push_back(newComer); dp2[newComer.first][newComer.second] = getDp(newComer); } waitingShit.pop_front(); } if (q.empty() && waitingShit.empty()) break; int x = q.front().first, y = q.front().second; q.pop_front(); for (int i = 0; i < 4; i++) { int nx = x + px[i], ny = y + py[i]; if (nx >= 0 && nx < n && ny >= 0 && ny < m && dp2[nx][ny] > dp2[x][y] + 1) { q.push_back(make_pair(nx, ny)); dp2[nx][ny] = dp2[x][y] + 1; } } } for (int i = 0; i < thisColor[color].size(); i++) { int x = thisColor[color][i].first, y = thisColor[color][i].second; dp[x][y] = dp2[x][y]; } } else { for (int i = 0; i < thisColor[color].size(); i++) for (int j = 0; j < thisColor[color - 1].size(); j++) { int x1 = thisColor[color][i].first, y1 = thisColor[color][i].second; int x2 = thisColor[color - 1][j].first, y2 = thisColor[color - 1][j].second; dp[x1][y1] = min(dp[x1][y1], dp[x2][y2] + dist(x1, y1, x2, y2)); } } } int ans = inf; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] == p) { ans = min(ans, dp[i][j]); } cout << ans; return 0; }
### Prompt Create a solution in CPP for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; void bad(string mes = "Impossible") { cout << mes; exit(0); } template <typename... T> void shit(T&... x) {} template <typename... T> void dec(T&... x) { shit(--x...); } template <typename... T> void inc(T&... x) { shit(++x...); } template <typename T> string bin(T x, int st = 2) { string ans = ""; while (x > 0) { ans += char('0' + x % st); x /= st; } reverse(ans.begin(), ans.end()); return ans.empty() ? "0" : ans; } template <typename T> T dcm(string& second) { T x = 0; for (int i = 0; i < second.size(); i++) { x = (x * 2) + (second[i] == '1'); } return x; } template <typename T> T input() { T ans = 0, m = 1; char c = ' '; while (c == ' ' || c == '\n') c = getchar(); if (c == '-') m = -1, c = getchar(); while (c >= '0' && c <= '9') { ans = ans * 10 + int(c - '0'), c = getchar(); } return ans * m; } const int inf = 1e9; const double eps = 1e-9; const int maxn = 3e2 + 10, base = 1e9 + 7; const int sigm = 26; const long long llinf = 1e18; template <typename T> T binpow(T n, T second) { if (second <= 0) return 1LL; if (second % 2 == 0) { T b = binpow(n, second / 2); return (1LL * b * b) % base; } else { return (1LL * binpow(n, second - 1) * n) % base; } } vector<pair<int, int> > thisColor[maxn * maxn]; int dp[maxn][maxn], dp2[maxn][maxn]; int a[maxn][maxn]; int dist(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } int getDp(const pair<int, int>& kek) { return dp[kek.first][kek.second]; } int getDp2(const pair<int, int>& kek) { return dp2[kek.first][kek.second]; } bool cmp(const pair<int, int>& a, const pair<int, int>& b) { return getDp(a) < getDp(b); } int px[4] = {1, 0, -1, 0}; int py[4] = {0, 1, 0, -1}; int main() { memset(dp, 63, sizeof(dp)); int n, m, p; scanf("%d %d %d", &n, &m, &p); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) dp[i][j] = i + j; thisColor[a[i][j]].push_back(make_pair(i, j)); } int block = (n + m) / 2; for (int color = 2; color <= p; color++) { if (thisColor[color].size() >= block || thisColor[color - 1].size() >= block) { deque<pair<int, int> > q, waitingShit; vector<pair<int, int> > tmp; for (int i = 0; i < thisColor[color - 1].size(); i++) tmp.push_back(thisColor[color - 1][i]); sort(tmp.begin(), tmp.end(), cmp); memset(dp2, 63, sizeof(dp2)); for (int i = 0; i < tmp.size(); i++) waitingShit.push_back(tmp[i]); while (!(q.empty() && waitingShit.empty())) { while (q.empty() || ((waitingShit.size()) && getDp(waitingShit.front()) <= getDp2(q.back()))) { if (q.empty() && waitingShit.empty()) break; pair<int, int> newComer = waitingShit.front(); if (dp2[newComer.first][newComer.second] > getDp(newComer)) { q.push_back(newComer); dp2[newComer.first][newComer.second] = getDp(newComer); } waitingShit.pop_front(); } if (q.empty() && waitingShit.empty()) break; int x = q.front().first, y = q.front().second; q.pop_front(); for (int i = 0; i < 4; i++) { int nx = x + px[i], ny = y + py[i]; if (nx >= 0 && nx < n && ny >= 0 && ny < m && dp2[nx][ny] > dp2[x][y] + 1) { q.push_back(make_pair(nx, ny)); dp2[nx][ny] = dp2[x][y] + 1; } } } for (int i = 0; i < thisColor[color].size(); i++) { int x = thisColor[color][i].first, y = thisColor[color][i].second; dp[x][y] = dp2[x][y]; } } else { for (int i = 0; i < thisColor[color].size(); i++) for (int j = 0; j < thisColor[color - 1].size(); j++) { int x1 = thisColor[color][i].first, y1 = thisColor[color][i].second; int x2 = thisColor[color - 1][j].first, y2 = thisColor[color - 1][j].second; dp[x1][y1] = min(dp[x1][y1], dp[x2][y2] + dist(x1, y1, x2, y2)); } } } int ans = inf; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] == p) { ans = min(ans, dp[i][j]); } cout << ans; return 0; } ```
#include <bits/stdc++.h> using namespace std; bool debug = 0; int n, m, k; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; string direc = "RDLU"; long long ln, lk, lm; void etp(bool f = 0) { puts(f ? "Yes" : "No"); exit(0); } void addmod(int &x, int y, int mod = 1000000007) { x += y; if (x >= mod) x -= mod; } void et() { puts("-1"); exit(0); } int a[305][305], p, dp[305][305], dis[305][305]; vector<pair<int, int>> mp[305 * 305]; bool vis[305][305]; bool cmp(pair<int, int> a, pair<int, int> b) { return dis[a.first][a.second] < dis[b.first][b.second]; } void add(pair<int, int> p, pair<int, int> q) { dp[q.first][q.second] = min(dp[q.first][q.second], dp[p.first][p.second] + abs(p.first - q.first) + abs(p.second - q.second)); } void cal(int lv) { if (mp[lv].size() * mp[lv + 1].size() <= m * n) { for (auto cur : mp[lv]) { for (auto pre : mp[lv + 1]) { add(pre, cur); } } } else { memset(vis, 0, sizeof vis); for (int(i) = 1; (i) <= (int)(n); (i)++) for (int(j) = 1; (j) <= (int)(m); (j)++) dis[i][j] = (1 << 30); map<int, vector<pair<int, int>>> tmp; for (auto pre : mp[lv + 1]) { dis[pre.first][pre.second] = dp[pre.first][pre.second]; tmp[dis[pre.first][pre.second]].push_back(pre); } for (auto &vec : tmp) { for (auto pre : vec.second) { int x = pre.first, y = pre.second; if (vis[x][y]) continue; vis[x][y] = 1; int D = dis[x][y]; for (int(k) = 0; (k) < (int)(4); (k)++) { int i = dx[k] + x, j = dy[k] + y; if (i < 1 || j < 1 || i > n || j > m) continue; if (D + 1 < dis[i][j]) { dis[i][j] = D + 1; tmp[D + 1].push_back({i, j}); } } } } for (auto cur : mp[lv]) { int x = cur.first, y = cur.second; dp[x][y] = dis[x][y]; } } } void fmain() { scanf("%d%d%d", &n, &m, &p); for (int(i) = 1; (i) <= (int)(n); (i)++) for (int(j) = 1; (j) <= (int)(m); (j)++) { scanf("%d", &a[i][j]); mp[a[i][j]].push_back({i, j}); dp[i][j] = (1 << 30); } for (auto x : mp[p]) { dp[x.first][x.second] = 0; } for (int i = p - 1; i; i--) cal(i); int ans = (1 << 30); for (auto p : mp[1]) { int x = p.first, y = p.second; ans = min(ans, dp[x][y] + abs(x - 1) + abs(y - 1)); } printf("%d\n", ans); } int main() { fmain(); return 0; }
### Prompt Your task is to create a cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; bool debug = 0; int n, m, k; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; string direc = "RDLU"; long long ln, lk, lm; void etp(bool f = 0) { puts(f ? "Yes" : "No"); exit(0); } void addmod(int &x, int y, int mod = 1000000007) { x += y; if (x >= mod) x -= mod; } void et() { puts("-1"); exit(0); } int a[305][305], p, dp[305][305], dis[305][305]; vector<pair<int, int>> mp[305 * 305]; bool vis[305][305]; bool cmp(pair<int, int> a, pair<int, int> b) { return dis[a.first][a.second] < dis[b.first][b.second]; } void add(pair<int, int> p, pair<int, int> q) { dp[q.first][q.second] = min(dp[q.first][q.second], dp[p.first][p.second] + abs(p.first - q.first) + abs(p.second - q.second)); } void cal(int lv) { if (mp[lv].size() * mp[lv + 1].size() <= m * n) { for (auto cur : mp[lv]) { for (auto pre : mp[lv + 1]) { add(pre, cur); } } } else { memset(vis, 0, sizeof vis); for (int(i) = 1; (i) <= (int)(n); (i)++) for (int(j) = 1; (j) <= (int)(m); (j)++) dis[i][j] = (1 << 30); map<int, vector<pair<int, int>>> tmp; for (auto pre : mp[lv + 1]) { dis[pre.first][pre.second] = dp[pre.first][pre.second]; tmp[dis[pre.first][pre.second]].push_back(pre); } for (auto &vec : tmp) { for (auto pre : vec.second) { int x = pre.first, y = pre.second; if (vis[x][y]) continue; vis[x][y] = 1; int D = dis[x][y]; for (int(k) = 0; (k) < (int)(4); (k)++) { int i = dx[k] + x, j = dy[k] + y; if (i < 1 || j < 1 || i > n || j > m) continue; if (D + 1 < dis[i][j]) { dis[i][j] = D + 1; tmp[D + 1].push_back({i, j}); } } } } for (auto cur : mp[lv]) { int x = cur.first, y = cur.second; dp[x][y] = dis[x][y]; } } } void fmain() { scanf("%d%d%d", &n, &m, &p); for (int(i) = 1; (i) <= (int)(n); (i)++) for (int(j) = 1; (j) <= (int)(m); (j)++) { scanf("%d", &a[i][j]); mp[a[i][j]].push_back({i, j}); dp[i][j] = (1 << 30); } for (auto x : mp[p]) { dp[x.first][x.second] = 0; } for (int i = p - 1; i; i--) cal(i); int ans = (1 << 30); for (auto p : mp[1]) { int x = p.first, y = p.second; ans = min(ans, dp[x][y] + abs(x - 1) + abs(y - 1)); } printf("%d\n", ans); } int main() { fmain(); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAXN = 305; int arr[MAXN][MAXN], cnt[MAXN * MAXN], dp[MAXN][MAXN], dis[MAXN][MAXN]; vector<pair<int, int> > cell[MAXN * MAXN]; int n, m; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; bool valid(int x, int y) { return 1 <= x && x <= n && 1 <= y && y <= m; } int main() { int p; scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &arr[i][j]); cnt[arr[i][j]]++; cell[arr[i][j]].push_back({i, j}); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (arr[i][j] == 1) dp[i][j] = i + j - 2; else dp[i][j] = 87654321; } int s = (int)sqrt(m * n); for (int k = 2; k <= p; k++) { if (cnt[k] <= s && cnt[k - 1] <= s) { for (auto &p1 : cell[k]) { for (auto &p2 : cell[k - 1]) { dp[p1.first][p1.second] = (((dp[p1.first][p1.second]) < (dp[p2.first][p2.second] + (((p1.first - p2.first) > 0) ? (p1.first - p2.first) : (-(p1.first - p2.first))) + (((p1.second - p2.second) > 0) ? (p1.second - p2.second) : (-(p1.second - p2.second))))) ? (dp[p1.first][p1.second]) : (dp[p2.first][p2.second] + (((p1.first - p2.first) > 0) ? (p1.first - p2.first) : (-(p1.first - p2.first))) + (((p1.second - p2.second) > 0) ? (p1.second - p2.second) : (-(p1.second - p2.second))))); } } } else { fill(dis[0], dis[0] + MAXN * MAXN, 87654321); queue<pair<int, int> > que; for (auto &p : cell[k - 1]) { que.push(p); dis[p.first][p.second] = dp[p.first][p.second]; } while (!que.empty()) { int x = que.front().first; int y = que.front().second; que.pop(); for (int dir = 0; dir < 4; dir++) { int nx = x + dx[dir]; int ny = y + dy[dir]; if (valid(nx, ny) && dis[nx][ny] > dis[x][y] + 1) { dis[nx][ny] = dis[x][y] + 1; que.push({nx, ny}); } } } for (auto &p : cell[k]) { dp[p.first][p.second] = dis[p.first][p.second]; } } } int ans = 87654321; for (auto &p : cell[p]) { ans = (((ans) < (dp[p.first][p.second])) ? (ans) : (dp[p.first][p.second])); } cout << ans; }
### Prompt Your challenge is to write a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 305; int arr[MAXN][MAXN], cnt[MAXN * MAXN], dp[MAXN][MAXN], dis[MAXN][MAXN]; vector<pair<int, int> > cell[MAXN * MAXN]; int n, m; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; bool valid(int x, int y) { return 1 <= x && x <= n && 1 <= y && y <= m; } int main() { int p; scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &arr[i][j]); cnt[arr[i][j]]++; cell[arr[i][j]].push_back({i, j}); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (arr[i][j] == 1) dp[i][j] = i + j - 2; else dp[i][j] = 87654321; } int s = (int)sqrt(m * n); for (int k = 2; k <= p; k++) { if (cnt[k] <= s && cnt[k - 1] <= s) { for (auto &p1 : cell[k]) { for (auto &p2 : cell[k - 1]) { dp[p1.first][p1.second] = (((dp[p1.first][p1.second]) < (dp[p2.first][p2.second] + (((p1.first - p2.first) > 0) ? (p1.first - p2.first) : (-(p1.first - p2.first))) + (((p1.second - p2.second) > 0) ? (p1.second - p2.second) : (-(p1.second - p2.second))))) ? (dp[p1.first][p1.second]) : (dp[p2.first][p2.second] + (((p1.first - p2.first) > 0) ? (p1.first - p2.first) : (-(p1.first - p2.first))) + (((p1.second - p2.second) > 0) ? (p1.second - p2.second) : (-(p1.second - p2.second))))); } } } else { fill(dis[0], dis[0] + MAXN * MAXN, 87654321); queue<pair<int, int> > que; for (auto &p : cell[k - 1]) { que.push(p); dis[p.first][p.second] = dp[p.first][p.second]; } while (!que.empty()) { int x = que.front().first; int y = que.front().second; que.pop(); for (int dir = 0; dir < 4; dir++) { int nx = x + dx[dir]; int ny = y + dy[dir]; if (valid(nx, ny) && dis[nx][ny] > dis[x][y] + 1) { dis[nx][ny] = dis[x][y] + 1; que.push({nx, ny}); } } } for (auto &p : cell[k]) { dp[p.first][p.second] = dis[p.first][p.second]; } } } int ans = 87654321; for (auto &p : cell[p]) { ans = (((ans) < (dp[p.first][p.second])) ? (ans) : (dp[p.first][p.second])); } cout << ans; } ```
#include <bits/stdc++.h> using namespace std; struct node { int x, y, d; node() { x = 0, y = 0, d = 0; } node(int a, int b, int c) { x = a, y = b, d = c; } bool operator<(const node &other) const { return d < other.d; } }; vector<node> dp[305 * 305]; int n, m, p, x; int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) scanf("%d", &x), dp[x].push_back(node(i, j, (int)1e9)); dp[0].push_back(node()); auto dist = [&](node a, node b) -> int { return abs(a.x - b.x) + abs(a.y - b.y); }; for (int i = 0; i < p; i++) { sort(dp[i].begin(), dp[i].end()); for (int j = 0; j < ((int)dp[i].size() < 600 ? (int)dp[i].size() : 600); j++) { for (auto &v : dp[i + 1]) { v.d = (v.d < dp[i][j].d + dist(v, dp[i][j]) ? v.d : dp[i][j].d + dist(v, dp[i][j])); } } } sort(dp[p].begin(), dp[p].end()); cout << dp[p][0].d << '\n'; return 0; }
### Prompt Create a solution in CPP for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct node { int x, y, d; node() { x = 0, y = 0, d = 0; } node(int a, int b, int c) { x = a, y = b, d = c; } bool operator<(const node &other) const { return d < other.d; } }; vector<node> dp[305 * 305]; int n, m, p, x; int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) scanf("%d", &x), dp[x].push_back(node(i, j, (int)1e9)); dp[0].push_back(node()); auto dist = [&](node a, node b) -> int { return abs(a.x - b.x) + abs(a.y - b.y); }; for (int i = 0; i < p; i++) { sort(dp[i].begin(), dp[i].end()); for (int j = 0; j < ((int)dp[i].size() < 600 ? (int)dp[i].size() : 600); j++) { for (auto &v : dp[i + 1]) { v.d = (v.d < dp[i][j].d + dist(v, dp[i][j]) ? v.d : dp[i][j].d + dist(v, dp[i][j])); } } } sort(dp[p].begin(), dp[p].end()); cout << dp[p][0].d << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; int ver[] = {0, 1, 0, -1}; int hor[] = {1, 0, -1, 0}; int main() { int n, m, p; cin >> n >> m >> p; vector<vector<int> > grid; grid.assign(n + 10, vector<int>(m + 10, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &grid[i][j]); } } vector<vector<int> > xpos(p + 10, vector<int>(0, 0)), ypos; ypos = xpos; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { xpos[grid[i][j]].push_back(i); ypos[grid[i][j]].push_back(j); } } vector<vector<int> > dis(n + 10, vector<int>(m + 10, 1000000000)); for (int j = 0; j < (int)xpos[1].size(); j++) { int ux = xpos[1][j]; int uy = ypos[1][j]; dis[ux][uy] = ux + uy; } for (int i = 1; i < p; i++) { if ((long long)xpos[i].size() * (long long)xpos[i + 1].size() > 200000LL) { priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; vector<int> dis2(n * m + 10, 1000000000); for (int j = 0; j < (int)xpos[i].size(); j++) { int ux = xpos[i][j]; int uy = ypos[i][j]; int u = ux * m + uy; dis2[u] = dis[ux][uy]; pq.push(pair<int, int>(dis2[u], u)); } while (!pq.empty()) { pair<int, int> f = pq.top(); pq.pop(); int d = f.first; int u = f.second; int ux = u / m; int uy = u % m; int t = grid[ux][uy]; for (int j = 0; j < 4; j++) { int vx = ux + hor[j]; int vy = uy + ver[j]; if (vx >= 0 && vx < n && vy >= 0 && vy < m) { int v = vx * m + vy; if (dis2[v] == 1000000000) { dis2[v] = dis2[u] + 1; pq.push(pair<int, int>(dis2[v], v)); if (grid[vx][vy] == i + 1) { dis[vx][vy] = min(dis[vx][vy], dis2[v]); } } } } } } else { for (int j = 0; j < (int)xpos[i].size(); j++) { int ux = xpos[i][j]; int uy = ypos[i][j]; for (int k = 0; k < (int)xpos[i + 1].size(); k++) { int vx = xpos[i + 1][k]; int vy = ypos[i + 1][k]; dis[vx][vy] = min(dis[vx][vy], dis[ux][uy] + abs(ux - vx) + abs(uy - vy)); } } } } cout << dis[xpos[p][0]][ypos[p][0]] << endl; return 0; }
### Prompt Generate a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int ver[] = {0, 1, 0, -1}; int hor[] = {1, 0, -1, 0}; int main() { int n, m, p; cin >> n >> m >> p; vector<vector<int> > grid; grid.assign(n + 10, vector<int>(m + 10, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &grid[i][j]); } } vector<vector<int> > xpos(p + 10, vector<int>(0, 0)), ypos; ypos = xpos; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { xpos[grid[i][j]].push_back(i); ypos[grid[i][j]].push_back(j); } } vector<vector<int> > dis(n + 10, vector<int>(m + 10, 1000000000)); for (int j = 0; j < (int)xpos[1].size(); j++) { int ux = xpos[1][j]; int uy = ypos[1][j]; dis[ux][uy] = ux + uy; } for (int i = 1; i < p; i++) { if ((long long)xpos[i].size() * (long long)xpos[i + 1].size() > 200000LL) { priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; vector<int> dis2(n * m + 10, 1000000000); for (int j = 0; j < (int)xpos[i].size(); j++) { int ux = xpos[i][j]; int uy = ypos[i][j]; int u = ux * m + uy; dis2[u] = dis[ux][uy]; pq.push(pair<int, int>(dis2[u], u)); } while (!pq.empty()) { pair<int, int> f = pq.top(); pq.pop(); int d = f.first; int u = f.second; int ux = u / m; int uy = u % m; int t = grid[ux][uy]; for (int j = 0; j < 4; j++) { int vx = ux + hor[j]; int vy = uy + ver[j]; if (vx >= 0 && vx < n && vy >= 0 && vy < m) { int v = vx * m + vy; if (dis2[v] == 1000000000) { dis2[v] = dis2[u] + 1; pq.push(pair<int, int>(dis2[v], v)); if (grid[vx][vy] == i + 1) { dis[vx][vy] = min(dis[vx][vy], dis2[v]); } } } } } } else { for (int j = 0; j < (int)xpos[i].size(); j++) { int ux = xpos[i][j]; int uy = ypos[i][j]; for (int k = 0; k < (int)xpos[i + 1].size(); k++) { int vx = xpos[i + 1][k]; int vy = ypos[i + 1][k]; dis[vx][vy] = min(dis[vx][vy], dis[ux][uy] + abs(ux - vx) + abs(uy - vy)); } } } } cout << dis[xpos[p][0]][ypos[p][0]] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int INF = (int)1e9; const long long INF64 = (long long)1e18; const long double eps = 1e-9; const long double pi = 3.14159265358979323846; const int MAXN = 300; int n, m, p, d[MAXN][MAXN], dist[MAXN][MAXN]; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; vector<vector<pair<int, int> > > chests; inline bool inside(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } bool read() { if (scanf("%d%d%d", &n, &m, &p) != 3) return false; for (int i = 0; i < int(300); ++i) { for (int j = 0; j < int(300); ++j) { d[i][j] = INF; } } chests.clear(); chests.resize(p); for (int i = 0; i < int(n); ++i) { for (int j = 0; j < int(m); ++j) { int v; scanf("%d", &v); v--; if (v == 0) { d[i][j] = i + j; } chests[v].push_back(make_pair(i, j)); } } return true; } void solve() { for (int i = 0; i < int(p - 1); ++i) { int current_size = (int)(chests[i]).size(); int next_size = (int)(chests[i + 1]).size(); if (current_size * next_size <= n * m) { for (int from = 0; from < int(current_size); ++from) { int fx = chests[i][from].first; int fy = chests[i][from].second; for (int to = 0; to < int(next_size); ++to) { int tx = chests[i + 1][to].first; int ty = chests[i + 1][to].second; d[tx][ty] = min(d[tx][ty], d[fx][fy] + abs(fx - tx) + abs(fy - ty)); } } } else { vector<pair<int, pair<int, int> > > candidates; for (int r = 0; r < int(n); ++r) { for (int c = 0; c < int(m); ++c) { dist[r][c] = -1; } } for (int from = 0; from < int(current_size); ++from) { int fx = chests[i][from].first; int fy = chests[i][from].second; candidates.push_back(make_pair(d[fx][fy], make_pair(fx, fy))); } sort((candidates).begin(), (candidates).end()); queue<pair<int, pair<int, int> > > q; int pointer = 1; q.push(candidates[0]); dist[candidates[0].second.first][candidates[0].second.second] = d[candidates[0].second.first][candidates[0].second.second]; while (!q.empty()) { int x = q.front().second.first; int y = q.front().second.second; q.pop(); while (pointer < current_size && candidates[pointer].first <= dist[x][y]) { int tx = candidates[pointer].second.first; int ty = candidates[pointer].second.second; q.push(candidates[pointer++]); dist[tx][ty] = d[tx][ty]; } for (int dir = 0; dir < int(4); ++dir) { int nx = x + dx[dir]; int ny = y + dy[dir]; int ndist = dist[x][y] + 1; if (inside(nx, ny) && dist[nx][ny] == -1) { dist[nx][ny] = ndist; q.push(make_pair(ndist, make_pair(nx, ny))); } } } for (int to = 0; to < int(next_size); ++to) { int x = chests[i + 1][to].first; int y = chests[i + 1][to].second; d[x][y] = dist[x][y]; } } } printf("%d\n", d[chests.back()[0].first][chests.back()[0].second]); } int main() { while (read()) solve(); return 0; }
### Prompt Please formulate a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = (int)1e9; const long long INF64 = (long long)1e18; const long double eps = 1e-9; const long double pi = 3.14159265358979323846; const int MAXN = 300; int n, m, p, d[MAXN][MAXN], dist[MAXN][MAXN]; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; vector<vector<pair<int, int> > > chests; inline bool inside(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } bool read() { if (scanf("%d%d%d", &n, &m, &p) != 3) return false; for (int i = 0; i < int(300); ++i) { for (int j = 0; j < int(300); ++j) { d[i][j] = INF; } } chests.clear(); chests.resize(p); for (int i = 0; i < int(n); ++i) { for (int j = 0; j < int(m); ++j) { int v; scanf("%d", &v); v--; if (v == 0) { d[i][j] = i + j; } chests[v].push_back(make_pair(i, j)); } } return true; } void solve() { for (int i = 0; i < int(p - 1); ++i) { int current_size = (int)(chests[i]).size(); int next_size = (int)(chests[i + 1]).size(); if (current_size * next_size <= n * m) { for (int from = 0; from < int(current_size); ++from) { int fx = chests[i][from].first; int fy = chests[i][from].second; for (int to = 0; to < int(next_size); ++to) { int tx = chests[i + 1][to].first; int ty = chests[i + 1][to].second; d[tx][ty] = min(d[tx][ty], d[fx][fy] + abs(fx - tx) + abs(fy - ty)); } } } else { vector<pair<int, pair<int, int> > > candidates; for (int r = 0; r < int(n); ++r) { for (int c = 0; c < int(m); ++c) { dist[r][c] = -1; } } for (int from = 0; from < int(current_size); ++from) { int fx = chests[i][from].first; int fy = chests[i][from].second; candidates.push_back(make_pair(d[fx][fy], make_pair(fx, fy))); } sort((candidates).begin(), (candidates).end()); queue<pair<int, pair<int, int> > > q; int pointer = 1; q.push(candidates[0]); dist[candidates[0].second.first][candidates[0].second.second] = d[candidates[0].second.first][candidates[0].second.second]; while (!q.empty()) { int x = q.front().second.first; int y = q.front().second.second; q.pop(); while (pointer < current_size && candidates[pointer].first <= dist[x][y]) { int tx = candidates[pointer].second.first; int ty = candidates[pointer].second.second; q.push(candidates[pointer++]); dist[tx][ty] = d[tx][ty]; } for (int dir = 0; dir < int(4); ++dir) { int nx = x + dx[dir]; int ny = y + dy[dir]; int ndist = dist[x][y] + 1; if (inside(nx, ny) && dist[nx][ny] == -1) { dist[nx][ny] = ndist; q.push(make_pair(ndist, make_pair(nx, ny))); } } } for (int to = 0; to < int(next_size); ++to) { int x = chests[i + 1][to].first; int y = chests[i + 1][to].second; d[x][y] = dist[x][y]; } } } printf("%d\n", d[chests.back()[0].first][chests.back()[0].second]); } int main() { while (read()) solve(); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAX = 3e2 + 1, INF = 2e9; int n, m, pm, d[MAX][MAX]; vector<pair<int, int>> t[MAX * MAX]; int val[MAX][MAX]; int delta[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; bool go(int x, int y) { return (x >= 0 && x < n && y >= 0 && y < m); } int main() { scanf("%d%d%d", &n, &m, &pm); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; scanf("%d", &x); t[x].push_back({i, j}); if (x == 1) d[i][j] = i + j; } for (int x = 2; x <= pm; x++) if ((int)(t[x - 1].size() * t[x].size()) > n * m) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) val[i][j] = INF; queue<pair<pair<int, int>, int>> q; for (auto p : t[x - 1]) { q.push({{p.first, p.second}, d[p.first][p.second]}); val[p.first][p.second] = d[p.first][p.second]; } while (!q.empty()) { auto p = q.front(); q.pop(); int i = p.first.first, j = p.first.second, v = p.second; if (val[i][j] != v) continue; for (int k = 0; k < 4; k++) { int ib = i + delta[k][0], jb = j + delta[k][1]; if (go(ib, jb) && val[ib][jb] > v + 1) { val[ib][jb] = v + 1; q.push({{ib, jb}, v + 1}); } } } for (auto p : t[x]) d[p.first][p.second] = val[p.first][p.second]; } else { for (auto p : t[x]) { int i = p.first, j = p.second; d[i][j] = INF; for (auto p2 : t[x - 1]) d[i][j] = min(d[i][j], d[p2.first][p2.second] + abs(i - p2.first) + abs(j - p2.second)); } } printf("%d\n", d[t[pm][0].first][t[pm][0].second]); return 0; }
### Prompt Generate a Cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAX = 3e2 + 1, INF = 2e9; int n, m, pm, d[MAX][MAX]; vector<pair<int, int>> t[MAX * MAX]; int val[MAX][MAX]; int delta[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; bool go(int x, int y) { return (x >= 0 && x < n && y >= 0 && y < m); } int main() { scanf("%d%d%d", &n, &m, &pm); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; scanf("%d", &x); t[x].push_back({i, j}); if (x == 1) d[i][j] = i + j; } for (int x = 2; x <= pm; x++) if ((int)(t[x - 1].size() * t[x].size()) > n * m) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) val[i][j] = INF; queue<pair<pair<int, int>, int>> q; for (auto p : t[x - 1]) { q.push({{p.first, p.second}, d[p.first][p.second]}); val[p.first][p.second] = d[p.first][p.second]; } while (!q.empty()) { auto p = q.front(); q.pop(); int i = p.first.first, j = p.first.second, v = p.second; if (val[i][j] != v) continue; for (int k = 0; k < 4; k++) { int ib = i + delta[k][0], jb = j + delta[k][1]; if (go(ib, jb) && val[ib][jb] > v + 1) { val[ib][jb] = v + 1; q.push({{ib, jb}, v + 1}); } } } for (auto p : t[x]) d[p.first][p.second] = val[p.first][p.second]; } else { for (auto p : t[x]) { int i = p.first, j = p.second; d[i][j] = INF; for (auto p2 : t[x - 1]) d[i][j] = min(d[i][j], d[p2.first][p2.second] + abs(i - p2.first) + abs(j - p2.second)); } } printf("%d\n", d[t[pm][0].first][t[pm][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 301, inf = 1e9 + 5; int dp[N][N]; int a[N][N]; vector<pair<int, int> > positions[N * N]; int n, m, p; int dis(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } void read() { cin >> n >> m >> p; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { int x; cin >> x; dp[i][j] = inf; a[i][j] = x; positions[x].push_back({i, j}); if (x == 1) dp[i][j] = i + j; } } void solve() { for (int cur = 1; cur < p; ++cur) { vector<int> next_positions[N]; vector<int> vis(N, 0); for (int i = 0; i < (int)positions[cur + 1].size(); ++i) { pair<int, int> tmp = positions[cur + 1][i]; next_positions[tmp.second].push_back(tmp.first); } for (int i = 0; i < (int)positions[cur].size(); ++i) { pair<int, int> tmp = positions[cur][i]; vis[tmp.first] = 1; } for (int i = 0; i < n; ++i) if (vis[i]) { int res = inf; for (int j = 0; j < m; ++j) { ++res; if (a[i][j] == cur) res = min(res, dp[i][j]); for (auto t : next_positions[j]) dp[t][j] = min(dp[t][j], res + (int)abs(t - i)); } res = inf; for (int j = m - 1; j >= 0; --j) { ++res; if (a[i][j] == cur) res = min(res, dp[i][j]); for (auto t : next_positions[j]) dp[t][j] = min(dp[t][j], res + (int)abs(t - i)); } } } cout << dp[positions[p][0].first][positions[p][0].second]; } int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); read(); solve(); return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 301, inf = 1e9 + 5; int dp[N][N]; int a[N][N]; vector<pair<int, int> > positions[N * N]; int n, m, p; int dis(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } void read() { cin >> n >> m >> p; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { int x; cin >> x; dp[i][j] = inf; a[i][j] = x; positions[x].push_back({i, j}); if (x == 1) dp[i][j] = i + j; } } void solve() { for (int cur = 1; cur < p; ++cur) { vector<int> next_positions[N]; vector<int> vis(N, 0); for (int i = 0; i < (int)positions[cur + 1].size(); ++i) { pair<int, int> tmp = positions[cur + 1][i]; next_positions[tmp.second].push_back(tmp.first); } for (int i = 0; i < (int)positions[cur].size(); ++i) { pair<int, int> tmp = positions[cur][i]; vis[tmp.first] = 1; } for (int i = 0; i < n; ++i) if (vis[i]) { int res = inf; for (int j = 0; j < m; ++j) { ++res; if (a[i][j] == cur) res = min(res, dp[i][j]); for (auto t : next_positions[j]) dp[t][j] = min(dp[t][j], res + (int)abs(t - i)); } res = inf; for (int j = m - 1; j >= 0; --j) { ++res; if (a[i][j] == cur) res = min(res, dp[i][j]); for (auto t : next_positions[j]) dp[t][j] = min(dp[t][j], res + (int)abs(t - i)); } } } cout << dp[positions[p][0].first][positions[p][0].second]; } int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); read(); solve(); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int maxn = 300 + 5; int n, m, p; int atlas[maxn][maxn]; vector<pair<int, int> > v[maxn * maxn]; int dp[maxn][maxn], dis[maxn][maxn]; bool vis[maxn][maxn]; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; int solve() { for (int i = 1; i < p; i++) { int len1 = v[i].size(); int len2 = v[i + 1].size(); if (len1 * len2 <= n * m) { for (int j = 0; j < len1; j++) { int jx = v[i][j].first, jy = v[i][j].second; for (int k = 0; k < len2; k++) { int kx = v[i + 1][k].first, ky = v[i + 1][k].second; dp[kx][ky] = min(dp[kx][ky], dp[jx][jy] + abs(kx - jx) + abs(ky - jy)); } } } else { memset(dis, -1, sizeof(dis)); memset(vis, false, sizeof(vis)); queue<pair<int, int> > que; for (int j = 0; j < len1; j++) { int jx = v[i][j].first, jy = v[i][j].second; dis[jx][jy] = dp[jx][jy]; que.push(make_pair(jx, jy)); vis[jx][jy] = true; } while (!que.empty()) { pair<int, int> u = que.front(); que.pop(); vis[u.first][u.second] = false; for (int j = 0; j < 4; j++) { int jx = u.first + dx[j], jy = u.second + dy[j]; if (jx <= 0 || jx > n || jy <= 0 || jy > m) continue; if (dis[jx][jy] == -1 || dis[jx][jy] > dis[u.first][u.second] + 1) { dis[jx][jy] = dis[u.first][u.second] + 1; if (!vis[jx][jy]) { vis[jx][jy] = true; que.push(make_pair(jx, jy)); } } } } for (int j = 0; j < len2; j++) { int jx = v[i + 1][j].first, jy = v[i + 1][j].second; dp[jx][jy] = min(dp[jx][jy], dis[jx][jy]); } } } int px = v[p][0].first, py = v[p][0].second; return dp[px][py]; } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int c; scanf("%d", &c); if (c == 1) dp[i][j] = i + j - 2; else dp[i][j] = inf; v[c].push_back(make_pair(i, j)); atlas[i][j] = c; } } printf("%d\n", solve()); return 0; }
### Prompt Develop a solution in cpp to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int maxn = 300 + 5; int n, m, p; int atlas[maxn][maxn]; vector<pair<int, int> > v[maxn * maxn]; int dp[maxn][maxn], dis[maxn][maxn]; bool vis[maxn][maxn]; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; int solve() { for (int i = 1; i < p; i++) { int len1 = v[i].size(); int len2 = v[i + 1].size(); if (len1 * len2 <= n * m) { for (int j = 0; j < len1; j++) { int jx = v[i][j].first, jy = v[i][j].second; for (int k = 0; k < len2; k++) { int kx = v[i + 1][k].first, ky = v[i + 1][k].second; dp[kx][ky] = min(dp[kx][ky], dp[jx][jy] + abs(kx - jx) + abs(ky - jy)); } } } else { memset(dis, -1, sizeof(dis)); memset(vis, false, sizeof(vis)); queue<pair<int, int> > que; for (int j = 0; j < len1; j++) { int jx = v[i][j].first, jy = v[i][j].second; dis[jx][jy] = dp[jx][jy]; que.push(make_pair(jx, jy)); vis[jx][jy] = true; } while (!que.empty()) { pair<int, int> u = que.front(); que.pop(); vis[u.first][u.second] = false; for (int j = 0; j < 4; j++) { int jx = u.first + dx[j], jy = u.second + dy[j]; if (jx <= 0 || jx > n || jy <= 0 || jy > m) continue; if (dis[jx][jy] == -1 || dis[jx][jy] > dis[u.first][u.second] + 1) { dis[jx][jy] = dis[u.first][u.second] + 1; if (!vis[jx][jy]) { vis[jx][jy] = true; que.push(make_pair(jx, jy)); } } } } for (int j = 0; j < len2; j++) { int jx = v[i + 1][j].first, jy = v[i + 1][j].second; dp[jx][jy] = min(dp[jx][jy], dis[jx][jy]); } } } int px = v[p][0].first, py = v[p][0].second; return dp[px][py]; } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int c; scanf("%d", &c); if (c == 1) dp[i][j] = i + j - 2; else dp[i][j] = inf; v[c].push_back(make_pair(i, j)); atlas[i][j] = c; } } printf("%d\n", solve()); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAXN = 200001; int dp[305][305], a[305][305]; int dist[305][305]; int n, m, k; vector<pair<int, int> > v[90001]; int dy[4] = {0, 0, 1, -1}; int dx[4] = {1, -1, 0, 0}; struct Node { int y, x, v; bool operator<(const Node &nd) const { return v > nd.v; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); for (int i = 0; i < 305; i++) for (int j = 0; j < 305; j++) dp[i][j] = 2e9; cin >> n >> m >> k; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> a[i][j]; if (a[i][j] == 1) dp[i][j] = i + j; v[a[i][j]].push_back({i, j}); } for (int i = 2; i <= k; i++) { if (v[i - 1].size() * v[i].size() > 5 * n * m) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { dist[i][j] = 2e9; } priority_queue<Node> pq; for (auto &p : v[i - 1]) { int y = p.first; int x = p.second; dist[y][x] = dp[y][x]; pq.push({y, x, dist[y][x]}); } while (!pq.empty()) { auto p = pq.top(); pq.pop(); int y = p.y; int x = p.x; int v = p.v; if (v > dist[y][x]) continue; for (int k = 0; k < 4; k++) { int ny = y + dy[k]; int nx = x + dx[k]; if (ny < 0 || ny >= n || nx < 0 || nx >= m) continue; if (dist[ny][nx] > dist[y][x] + 1) { dist[ny][nx] = dist[y][x] + 1; pq.push({ny, nx, dist[ny][nx]}); } } } for (auto &p : v[i]) { int y = p.first; int x = p.second; dp[y][x] = dist[y][x]; } } else { for (auto &p1 : v[i - 1]) { int y1 = p1.first; int x1 = p1.second; for (auto p2 : v[i]) { int y2 = p2.first; int x2 = p2.second; dp[y2][x2] = min(dp[y2][x2], dp[y1][x1] + abs(y1 - y2) + abs(x1 - x2)); } } } } int ans = 2e9; for (auto &p : v[k]) { int y = p.first; int x = p.second; ans = min(ans, dp[y][x]); } cout << ans; return 0; }
### Prompt Generate a cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 200001; int dp[305][305], a[305][305]; int dist[305][305]; int n, m, k; vector<pair<int, int> > v[90001]; int dy[4] = {0, 0, 1, -1}; int dx[4] = {1, -1, 0, 0}; struct Node { int y, x, v; bool operator<(const Node &nd) const { return v > nd.v; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); for (int i = 0; i < 305; i++) for (int j = 0; j < 305; j++) dp[i][j] = 2e9; cin >> n >> m >> k; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> a[i][j]; if (a[i][j] == 1) dp[i][j] = i + j; v[a[i][j]].push_back({i, j}); } for (int i = 2; i <= k; i++) { if (v[i - 1].size() * v[i].size() > 5 * n * m) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { dist[i][j] = 2e9; } priority_queue<Node> pq; for (auto &p : v[i - 1]) { int y = p.first; int x = p.second; dist[y][x] = dp[y][x]; pq.push({y, x, dist[y][x]}); } while (!pq.empty()) { auto p = pq.top(); pq.pop(); int y = p.y; int x = p.x; int v = p.v; if (v > dist[y][x]) continue; for (int k = 0; k < 4; k++) { int ny = y + dy[k]; int nx = x + dx[k]; if (ny < 0 || ny >= n || nx < 0 || nx >= m) continue; if (dist[ny][nx] > dist[y][x] + 1) { dist[ny][nx] = dist[y][x] + 1; pq.push({ny, nx, dist[ny][nx]}); } } } for (auto &p : v[i]) { int y = p.first; int x = p.second; dp[y][x] = dist[y][x]; } } else { for (auto &p1 : v[i - 1]) { int y1 = p1.first; int x1 = p1.second; for (auto p2 : v[i]) { int y2 = p2.first; int x2 = p2.second; dp[y2][x2] = min(dp[y2][x2], dp[y1][x1] + abs(y1 - y2) + abs(x1 - x2)); } } } } int ans = 2e9; for (auto &p : v[k]) { int y = p.first; int x = p.second; ans = min(ans, dp[y][x]); } cout << ans; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}; int ex[300000], ey[300000], nxt[300000], first[300000]; int ux[300000], uy[300000], uxt[300000], uirst[3000]; int c[300000], d[600][600], e[600][600]; int i, j, k, l, m, n, o, r, s, t, x, y, sum_edge, sum_udge; inline void addedge(int x, int y, int z) { sum_edge++, ex[sum_edge] = x, ey[sum_edge] = y, nxt[sum_edge] = first[z], first[z] = sum_edge; return; } inline void addudge(int x, int y, int z) { sum_udge++, ux[sum_udge] = x, uy[sum_udge] = y, uxt[sum_udge] = uirst[z], uirst[z] = sum_udge; return; } int main() { scanf("%d%d%d", &n, &m, &o); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) scanf("%d", &t), addedge(i, j, t), c[t]++; memset(d, 12, sizeof(d)), s = 100000000; for (i = first[1]; i != 0; i = nxt[i]) d[ex[i]][ey[i]] = ex[i] + ey[i] - 2; for (i = 1; i < o; i++) { if (c[i] * c[i + 1] < n * m) for (j = first[i]; j != 0; j = nxt[j]) for (k = first[i + 1]; k != 0; k = nxt[k]) d[ex[k]][ey[k]] = min(d[ex[k]][ey[k]], d[ex[j]][ey[j]] + abs(ex[j] - ex[k]) + abs(ey[j] - ey[k])); else { r = 100000000; for (j = first[i]; j != 0; j = nxt[j]) r = min(r, d[ex[j]][ey[j]]); memset(e, 255, sizeof(e)); memset(uirst, 0, sizeof(uirst)); sum_udge = 0; for (j = first[i]; j != 0; j = nxt[j]) addudge(ex[j], ey[j], d[ex[j]][ey[j]] - r), e[ex[j]][ey[j]] = d[ex[j]][ey[j]] - r; for (j = 0; j < n + m; j++) for (k = uirst[j]; k != 0; k = uxt[k]) for (l = 0; l < 4; l++) { x = ux[k] + dx[l], y = uy[k] + dy[l]; if ((x > 0) && (x <= n) && (y > 0) && (y <= m) && (!(~e[x][y]))) addudge(x, y, j + 1), e[x][y] = j + 1; } for (j = first[i + 1]; j != 0; j = nxt[j]) d[ex[j]][ey[j]] = e[ex[j]][ey[j]] + r; } } for (i = first[o]; i != 0; i = nxt[i]) s = min(s, d[ex[i]][ey[i]]); printf("%d", s); return 0; }
### Prompt Develop a solution in cpp to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}; int ex[300000], ey[300000], nxt[300000], first[300000]; int ux[300000], uy[300000], uxt[300000], uirst[3000]; int c[300000], d[600][600], e[600][600]; int i, j, k, l, m, n, o, r, s, t, x, y, sum_edge, sum_udge; inline void addedge(int x, int y, int z) { sum_edge++, ex[sum_edge] = x, ey[sum_edge] = y, nxt[sum_edge] = first[z], first[z] = sum_edge; return; } inline void addudge(int x, int y, int z) { sum_udge++, ux[sum_udge] = x, uy[sum_udge] = y, uxt[sum_udge] = uirst[z], uirst[z] = sum_udge; return; } int main() { scanf("%d%d%d", &n, &m, &o); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) scanf("%d", &t), addedge(i, j, t), c[t]++; memset(d, 12, sizeof(d)), s = 100000000; for (i = first[1]; i != 0; i = nxt[i]) d[ex[i]][ey[i]] = ex[i] + ey[i] - 2; for (i = 1; i < o; i++) { if (c[i] * c[i + 1] < n * m) for (j = first[i]; j != 0; j = nxt[j]) for (k = first[i + 1]; k != 0; k = nxt[k]) d[ex[k]][ey[k]] = min(d[ex[k]][ey[k]], d[ex[j]][ey[j]] + abs(ex[j] - ex[k]) + abs(ey[j] - ey[k])); else { r = 100000000; for (j = first[i]; j != 0; j = nxt[j]) r = min(r, d[ex[j]][ey[j]]); memset(e, 255, sizeof(e)); memset(uirst, 0, sizeof(uirst)); sum_udge = 0; for (j = first[i]; j != 0; j = nxt[j]) addudge(ex[j], ey[j], d[ex[j]][ey[j]] - r), e[ex[j]][ey[j]] = d[ex[j]][ey[j]] - r; for (j = 0; j < n + m; j++) for (k = uirst[j]; k != 0; k = uxt[k]) for (l = 0; l < 4; l++) { x = ux[k] + dx[l], y = uy[k] + dy[l]; if ((x > 0) && (x <= n) && (y > 0) && (y <= m) && (!(~e[x][y]))) addudge(x, y, j + 1), e[x][y] = j + 1; } for (j = first[i + 1]; j != 0; j = nxt[j]) d[ex[j]][ey[j]] = e[ex[j]][ey[j]] + r; } } for (i = first[o]; i != 0; i = nxt[i]) s = min(s, d[ex[i]][ey[i]]); printf("%d", s); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int mod1 = 1e9 + 7, mod2 = 998244353, maxn = 305, maxlog = 20, K = 26; const long long infll = 1e18; const double pi = acos(-1); int n, m, p, a[maxn][maxn], fin_dist[maxn][maxn], dist[maxn][maxn]; int dx[] = {-1, 0, 0, 1}; int dy[] = {0, -1, 1, 0}; vector<pair<int, int> > luu[maxn * maxn]; void solve() { cin >> n >> m >> p; for (long long i = 1; i <= n; ++i) { for (long long j = 1; j <= m; ++j) { cin >> a[i][j]; luu[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) fin_dist[i][j] = i + j - 2; else fin_dist[i][j] = mod1; } } for (long long x = 1; x < p; ++x) { if (luu[x].size() * luu[x + 1].size() > m * n) { for (long long i = 1; i <= n; ++i) { for (long long j = 1; j <= m; ++j) { dist[i][j] = mod1; } } queue<pair<int, int> > q; for (auto v : luu[x]) { q.push(v); dist[v.first][v.second] = fin_dist[v.first][v.second]; } while (q.size()) { pair<int, int> now = q.front(); q.pop(); for (long long i = 0; i < 4; ++i) { int tx = now.first + dx[i], ty = now.second + dy[i]; if (tx < 1 || tx > n || ty < 1 || ty > m) { continue; } if (dist[tx][ty] > dist[now.first][now.second] + 1) { dist[tx][ty] = dist[now.first][now.second] + 1; q.push(make_pair(tx, ty)); if (a[tx][ty] == x + 1) { fin_dist[tx][ty] = dist[tx][ty]; } } } } } else { for (auto v1 : luu[x + 1]) { for (auto v2 : luu[x]) { fin_dist[v1.first][v1.second] = min(fin_dist[v1.first][v1.second], fin_dist[v2.first][v2.second] + abs(v2.first - v1.first) + abs(v2.second - v1.second)); } } } } int ans = mod1; for (long long i = 1; i <= n; ++i) { for (long long j = 1; j <= m; ++j) { if (a[i][j] == p) { ans = min(ans, fin_dist[i][j]); } } } cout << ans; } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); solve(); }
### Prompt Your task is to create a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int mod1 = 1e9 + 7, mod2 = 998244353, maxn = 305, maxlog = 20, K = 26; const long long infll = 1e18; const double pi = acos(-1); int n, m, p, a[maxn][maxn], fin_dist[maxn][maxn], dist[maxn][maxn]; int dx[] = {-1, 0, 0, 1}; int dy[] = {0, -1, 1, 0}; vector<pair<int, int> > luu[maxn * maxn]; void solve() { cin >> n >> m >> p; for (long long i = 1; i <= n; ++i) { for (long long j = 1; j <= m; ++j) { cin >> a[i][j]; luu[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) fin_dist[i][j] = i + j - 2; else fin_dist[i][j] = mod1; } } for (long long x = 1; x < p; ++x) { if (luu[x].size() * luu[x + 1].size() > m * n) { for (long long i = 1; i <= n; ++i) { for (long long j = 1; j <= m; ++j) { dist[i][j] = mod1; } } queue<pair<int, int> > q; for (auto v : luu[x]) { q.push(v); dist[v.first][v.second] = fin_dist[v.first][v.second]; } while (q.size()) { pair<int, int> now = q.front(); q.pop(); for (long long i = 0; i < 4; ++i) { int tx = now.first + dx[i], ty = now.second + dy[i]; if (tx < 1 || tx > n || ty < 1 || ty > m) { continue; } if (dist[tx][ty] > dist[now.first][now.second] + 1) { dist[tx][ty] = dist[now.first][now.second] + 1; q.push(make_pair(tx, ty)); if (a[tx][ty] == x + 1) { fin_dist[tx][ty] = dist[tx][ty]; } } } } } else { for (auto v1 : luu[x + 1]) { for (auto v2 : luu[x]) { fin_dist[v1.first][v1.second] = min(fin_dist[v1.first][v1.second], fin_dist[v2.first][v2.second] + abs(v2.first - v1.first) + abs(v2.second - v1.second)); } } } } int ans = mod1; for (long long i = 1; i <= n; ++i) { for (long long j = 1; j <= m; ++j) { if (a[i][j] == p) { ans = min(ans, fin_dist[i][j]); } } } cout << ans; } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); solve(); } ```
#include <bits/stdc++.h> using namespace std; int i, j, n, h, x, y, cur_h, k, m, p, fx, fy; int a[505][505], dp[505][505], d[505][505]; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; vector<pair<int, int> > g[250505]; vector<pair<int, pair<int, int> > > lst, bfs; int Abs(int x) { return x > 0 ? x : -x; } int find_dist(int x1, int y1, int x2, int y2) { return Abs(x1 - x2) + Abs(y1 - y2); } bool in_range(int x, int y) { return (x >= 0 && x < y); } int main() { cin >> n >> m >> p; for (i = 0; i < n; i++) for (j = 0; j < m; j++) dp[i][j] = (int)1e+9; for (i = 0; i < n; i++) for (j = 0; j < m; j++) { scanf("%d", &a[i][j]); g[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) dp[i][j] = i + j; if (a[i][j] == p) fx = i, fy = j; } for (i = 2; i <= p; i++) { int cur_size = g[i].size(); int last_size = g[i - 1].size(); if (cur_size * last_size < n * m) { for (j = 0; j < cur_size; j++) { int cur_x = g[i][j].first; int cur_y = g[i][j].second; for (k = 0; k < last_size; k++) { int last_x = g[i - 1][k].first; int last_y = g[i - 1][k].second; dp[cur_x][cur_y] = min(dp[cur_x][cur_y], dp[last_x][last_y] + find_dist(cur_x, cur_y, last_x, last_y)); } } } else { for (k = 0; k < n; k++) for (j = 0; j < m; j++) d[k][j] = -1; bfs.clear(); lst.clear(); for (j = 0; j < last_size; j++) { int last_x = g[i - 1][j].first; int last_y = g[i - 1][j].second; lst.push_back(make_pair(dp[last_x][last_y], make_pair(last_x, last_y))); } sort(lst.begin(), lst.end()); int pointer = 1; j = 0; bfs.push_back(lst[0]); d[lst[0].second.first][lst[0].second.second] = lst[0].first; while (j < bfs.size()) { int x = bfs[j].second.first; int y = bfs[j].second.second; int val = bfs[j].first; j++; while (pointer < lst.size() && lst[pointer].first <= val) bfs.push_back(lst[pointer++]); for (k = 0; k < 4; k++) if (in_range(x + dir[k][0], n) && in_range(y + dir[k][1], m) && d[x + dir[k][0]][y + dir[k][1]] == -1) { d[x + dir[k][0]][y + dir[k][1]] = val + 1; bfs.push_back( make_pair(val + 1, make_pair(x + dir[k][0], y + dir[k][1]))); } } for (j = 0; j < cur_size; j++) { int cur_x = g[i][j].first; int cur_y = g[i][j].second; dp[cur_x][cur_y] = d[cur_x][cur_y]; } } } cout << dp[fx][fy] << endl; return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int i, j, n, h, x, y, cur_h, k, m, p, fx, fy; int a[505][505], dp[505][505], d[505][505]; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; vector<pair<int, int> > g[250505]; vector<pair<int, pair<int, int> > > lst, bfs; int Abs(int x) { return x > 0 ? x : -x; } int find_dist(int x1, int y1, int x2, int y2) { return Abs(x1 - x2) + Abs(y1 - y2); } bool in_range(int x, int y) { return (x >= 0 && x < y); } int main() { cin >> n >> m >> p; for (i = 0; i < n; i++) for (j = 0; j < m; j++) dp[i][j] = (int)1e+9; for (i = 0; i < n; i++) for (j = 0; j < m; j++) { scanf("%d", &a[i][j]); g[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) dp[i][j] = i + j; if (a[i][j] == p) fx = i, fy = j; } for (i = 2; i <= p; i++) { int cur_size = g[i].size(); int last_size = g[i - 1].size(); if (cur_size * last_size < n * m) { for (j = 0; j < cur_size; j++) { int cur_x = g[i][j].first; int cur_y = g[i][j].second; for (k = 0; k < last_size; k++) { int last_x = g[i - 1][k].first; int last_y = g[i - 1][k].second; dp[cur_x][cur_y] = min(dp[cur_x][cur_y], dp[last_x][last_y] + find_dist(cur_x, cur_y, last_x, last_y)); } } } else { for (k = 0; k < n; k++) for (j = 0; j < m; j++) d[k][j] = -1; bfs.clear(); lst.clear(); for (j = 0; j < last_size; j++) { int last_x = g[i - 1][j].first; int last_y = g[i - 1][j].second; lst.push_back(make_pair(dp[last_x][last_y], make_pair(last_x, last_y))); } sort(lst.begin(), lst.end()); int pointer = 1; j = 0; bfs.push_back(lst[0]); d[lst[0].second.first][lst[0].second.second] = lst[0].first; while (j < bfs.size()) { int x = bfs[j].second.first; int y = bfs[j].second.second; int val = bfs[j].first; j++; while (pointer < lst.size() && lst[pointer].first <= val) bfs.push_back(lst[pointer++]); for (k = 0; k < 4; k++) if (in_range(x + dir[k][0], n) && in_range(y + dir[k][1], m) && d[x + dir[k][0]][y + dir[k][1]] == -1) { d[x + dir[k][0]][y + dir[k][1]] = val + 1; bfs.push_back( make_pair(val + 1, make_pair(x + dir[k][0], y + dir[k][1]))); } } for (j = 0; j < cur_size; j++) { int cur_x = g[i][j].first; int cur_y = g[i][j].second; dp[cur_x][cur_y] = d[cur_x][cur_y]; } } } cout << dp[fx][fy] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p, from[333]; vector<pair<int, int> > a[333 * 333], d[2][3333]; int main() { scanf("%d%d%d", &n, &m, &p); int J = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int k; scanf("%d", &k); a[k - 1].push_back({i, j}); if (k == p) J = j; } } d[0][0].push_back({0, 0}); for (int P = 0; P < p; P++) { for (int y = 0; y < m; y++) { d[!(P & 1)][y].clear(); from[y] = 0; } for (pair<int, int> cl : a[P]) { int X = cl.first, Y = cl.second, mcost = 1e9; for (int y = 0; y < m; y++) { int vn = d[P & 1][y].size(); while (from[y] + 1 < vn && d[P & 1][y][from[y] + 1].first <= X) from[y]++; if (from[y] < vn) mcost = min(mcost, d[P & 1][y][from[y]].second + abs(d[P & 1][y][from[y]].first - X) + abs(y - Y)); if (from[y] + 1 < vn) mcost = min(mcost, d[P & 1][y][from[y] + 1].second + abs(d[P & 1][y][from[y] + 1].first - X) + abs(y - Y)); } d[!(P & 1)][Y].push_back({X, mcost}); } } printf("%d", d[p & 1][J][0].second); }
### Prompt Your challenge is to write a Cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, p, from[333]; vector<pair<int, int> > a[333 * 333], d[2][3333]; int main() { scanf("%d%d%d", &n, &m, &p); int J = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int k; scanf("%d", &k); a[k - 1].push_back({i, j}); if (k == p) J = j; } } d[0][0].push_back({0, 0}); for (int P = 0; P < p; P++) { for (int y = 0; y < m; y++) { d[!(P & 1)][y].clear(); from[y] = 0; } for (pair<int, int> cl : a[P]) { int X = cl.first, Y = cl.second, mcost = 1e9; for (int y = 0; y < m; y++) { int vn = d[P & 1][y].size(); while (from[y] + 1 < vn && d[P & 1][y][from[y] + 1].first <= X) from[y]++; if (from[y] < vn) mcost = min(mcost, d[P & 1][y][from[y]].second + abs(d[P & 1][y][from[y]].first - X) + abs(y - Y)); if (from[y] + 1 < vn) mcost = min(mcost, d[P & 1][y][from[y] + 1].second + abs(d[P & 1][y][from[y] + 1].first - X) + abs(y - Y)); } d[!(P & 1)][Y].push_back({X, mcost}); } } printf("%d", d[p & 1][J][0].second); } ```
#include <bits/stdc++.h> using namespace std; using ll = long long; using ii = pair<int, int>; void in(int &x); const int N = 305; const int INF = 1e9 + 50; const int MOD = 1e9 + 7; int n, m, p; int grid[N][N], dp[N][N], dst[N][N]; vector<ii> pos[N * N]; int dr[] = {-1, 1, 0, 0}; int dc[] = {0, 0, -1, 1}; struct State { int row, col, dist; }; bool cmp(State a, State b) { return a.dist < b.dist; } int dist(int r1, int c1, int r2, int c2) { return abs(r1 - r2) + abs(c1 - c2); } bool inside(int r, int c) { return r >= 1 && r <= n && c >= 1 && c <= m; } void Process(int curTresure) { vector<State> elm; for (ii point : pos[curTresure - 1]) { elm.push_back({point.first, point.second, dp[point.first][point.second]}); } sort(elm.begin(), elm.end(), cmp); queue<State> bfs; int idx = 1; memset(dst, -1, sizeof dst); bfs.push(elm[0]); dst[elm[0].row][elm[0].col] = elm[0].dist; while (bfs.size()) { State cur = bfs.front(); bfs.pop(); int r = cur.row, c = cur.col, cd = cur.dist; while (idx < elm.size() && elm[idx].dist == cd) { bfs.push(elm[idx++]); } for (int i = 0; i < 4; i++) { int nr = r + dr[i], nc = c + dc[i]; if (!inside(nr, nc)) continue; if (dst[nr][nc] != -1) continue; dst[nr][nc] = cd + 1; bfs.push({nr, nc, cd + 1}); } } for (ii now : pos[curTresure]) { dp[now.first][now.second] = dst[now.first][now.second]; } } int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &grid[i][j]); pos[grid[i][j]].push_back({i, j}); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dp[i][j] = INF; if (grid[i][j] == 1) { dp[i][j] = dist(i, j, 1, 1); } } } for (int i = 2; i <= p; i++) { if (pos[i].size() * pos[i - 1].size() <= n * m) { for (ii point : pos[i]) { int r = point.first, c = point.second; for (ii prevPoint : pos[i - 1]) { int pr = prevPoint.first, pc = prevPoint.second; dp[r][c] = min(dp[pr][pc] + dist(pr, pc, r, c), dp[r][c]); } } } else { Process(i); } } int ans = INF; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (grid[i][j] < p) continue; ans = min(ans, dp[i][j]); } } printf(ans >= INF ? "-1\n" : "%d\n", ans); return 0; } void in(int &x) { bool neg = false; register int c; x = 0; c = getchar(); if (c == '-') { neg = true; c = getchar(); } for (; c > 47 && c < 58; c = getchar()) x = (x << 1) + (x << 3) + c - 48; if (neg) x *= -1; }
### Prompt Your challenge is to write a Cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; using ll = long long; using ii = pair<int, int>; void in(int &x); const int N = 305; const int INF = 1e9 + 50; const int MOD = 1e9 + 7; int n, m, p; int grid[N][N], dp[N][N], dst[N][N]; vector<ii> pos[N * N]; int dr[] = {-1, 1, 0, 0}; int dc[] = {0, 0, -1, 1}; struct State { int row, col, dist; }; bool cmp(State a, State b) { return a.dist < b.dist; } int dist(int r1, int c1, int r2, int c2) { return abs(r1 - r2) + abs(c1 - c2); } bool inside(int r, int c) { return r >= 1 && r <= n && c >= 1 && c <= m; } void Process(int curTresure) { vector<State> elm; for (ii point : pos[curTresure - 1]) { elm.push_back({point.first, point.second, dp[point.first][point.second]}); } sort(elm.begin(), elm.end(), cmp); queue<State> bfs; int idx = 1; memset(dst, -1, sizeof dst); bfs.push(elm[0]); dst[elm[0].row][elm[0].col] = elm[0].dist; while (bfs.size()) { State cur = bfs.front(); bfs.pop(); int r = cur.row, c = cur.col, cd = cur.dist; while (idx < elm.size() && elm[idx].dist == cd) { bfs.push(elm[idx++]); } for (int i = 0; i < 4; i++) { int nr = r + dr[i], nc = c + dc[i]; if (!inside(nr, nc)) continue; if (dst[nr][nc] != -1) continue; dst[nr][nc] = cd + 1; bfs.push({nr, nc, cd + 1}); } } for (ii now : pos[curTresure]) { dp[now.first][now.second] = dst[now.first][now.second]; } } int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &grid[i][j]); pos[grid[i][j]].push_back({i, j}); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dp[i][j] = INF; if (grid[i][j] == 1) { dp[i][j] = dist(i, j, 1, 1); } } } for (int i = 2; i <= p; i++) { if (pos[i].size() * pos[i - 1].size() <= n * m) { for (ii point : pos[i]) { int r = point.first, c = point.second; for (ii prevPoint : pos[i - 1]) { int pr = prevPoint.first, pc = prevPoint.second; dp[r][c] = min(dp[pr][pc] + dist(pr, pc, r, c), dp[r][c]); } } } else { Process(i); } } int ans = INF; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (grid[i][j] < p) continue; ans = min(ans, dp[i][j]); } } printf(ans >= INF ? "-1\n" : "%d\n", ans); return 0; } void in(int &x) { bool neg = false; register int c; x = 0; c = getchar(); if (c == '-') { neg = true; c = getchar(); } for (; c > 47 && c < 58; c = getchar()) x = (x << 1) + (x << 3) + c - 48; if (neg) x *= -1; } ```
#include <bits/stdc++.h> using namespace std; int ar[305][305]; vector<pair<int, int> > poss[90005]; int dp[305][305]; vector<int> col[305]; int vis[305]; int n, m, p; void pr() {} void solve() { memset(dp, 127, sizeof(dp)); ; scanf("%d %d %d", &n, &m, &p); for (int i = 0; i < (int)(n); i++) { for (int j = 0; j < (int)(m); j++) { scanf("%d", &ar[i][j]); poss[ar[i][j]].push_back(make_pair(i, j)); if (ar[i][j] == 1) { dp[i][j] = i + j; } } } for (int val = 2; val <= p; val++) { memset(vis, 0, sizeof(vis)); ; for (int i = 0; i < (int)(m); i++) { col[i].clear(); } for (int i = 0; i < poss[val].size(); i++) { pair<int, int> a = poss[val][i]; col[a.second].push_back(a.first); } for (int i = 0; i < poss[val - 1].size(); i++) { pair<int, int> a = poss[val - 1][i]; vis[a.first] = 1; } for (int i = 0; i < n; i++) { if (!vis[i]) continue; int best = 1e9; for (int j = 0; j < m; j++) { best++; if (ar[i][j] == val - 1) best = min(best, dp[i][j]); for (int k = 0; k < col[j].size(); k++) { dp[col[j][k]][j] = min(dp[col[j][k]][j], best + abs(col[j][k] - i)); } } best = 1e9; for (int j = m; j >= 0; j--) { best++; if (ar[i][j] == val - 1) best = min(best, dp[i][j]); for (int k = 0; k < col[j].size(); k++) { dp[col[j][k]][j] = min(dp[col[j][k]][j], best + abs(col[j][k] - i)); } } } } printf("%d", dp[poss[p][0].first][poss[p][0].second]); } int main() { int TC = 1; for (int ZZ = 1; ZZ <= TC; ZZ++) { solve(); } return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int ar[305][305]; vector<pair<int, int> > poss[90005]; int dp[305][305]; vector<int> col[305]; int vis[305]; int n, m, p; void pr() {} void solve() { memset(dp, 127, sizeof(dp)); ; scanf("%d %d %d", &n, &m, &p); for (int i = 0; i < (int)(n); i++) { for (int j = 0; j < (int)(m); j++) { scanf("%d", &ar[i][j]); poss[ar[i][j]].push_back(make_pair(i, j)); if (ar[i][j] == 1) { dp[i][j] = i + j; } } } for (int val = 2; val <= p; val++) { memset(vis, 0, sizeof(vis)); ; for (int i = 0; i < (int)(m); i++) { col[i].clear(); } for (int i = 0; i < poss[val].size(); i++) { pair<int, int> a = poss[val][i]; col[a.second].push_back(a.first); } for (int i = 0; i < poss[val - 1].size(); i++) { pair<int, int> a = poss[val - 1][i]; vis[a.first] = 1; } for (int i = 0; i < n; i++) { if (!vis[i]) continue; int best = 1e9; for (int j = 0; j < m; j++) { best++; if (ar[i][j] == val - 1) best = min(best, dp[i][j]); for (int k = 0; k < col[j].size(); k++) { dp[col[j][k]][j] = min(dp[col[j][k]][j], best + abs(col[j][k] - i)); } } best = 1e9; for (int j = m; j >= 0; j--) { best++; if (ar[i][j] == val - 1) best = min(best, dp[i][j]); for (int k = 0; k < col[j].size(); k++) { dp[col[j][k]][j] = min(dp[col[j][k]][j], best + abs(col[j][k] - i)); } } } } printf("%d", dp[poss[p][0].first][poss[p][0].second]); } int main() { int TC = 1; for (int ZZ = 1; ZZ <= TC; ZZ++) { solve(); } return 0; } ```
#include <bits/stdc++.h> using namespace std; template <class T, class L> bool smax(T &x, L y) { return x < y ? (x = y, 1) : 0; } template <class T, class L> bool smin(T &x, L y) { return y < x ? (x = y, 1) : 0; } const int maxn = 3e2 + 17, maxp = maxn * maxn, inf = 2e9; struct st { int x, y, d; }; inline int sina_says_chra(const int &x) { return x >= 0 ? x : -x; } int n, p, m; vector<st> v[maxp]; bool mark[maxp]; int main() { ios::sync_with_stdio(0), cin.tie(0); v[0].push_back({0, 0, 0}); cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0, x; j < m; j++) cin >> x, v[x].push_back({i, j, inf}); for (int i = 1; i <= p; i++) { for (auto &x : v[i]) for (auto &y : v[i - 1]) smin(x.d, y.d + sina_says_chra(y.x - x.x) + sina_says_chra(y.y - x.y)); for (int j = 0; j < v[i].size(); j++) { mark[j] = 0; st &x = v[i][j]; for (auto &y : v[i]) if ((x.x != y.x || x.y != y.y) && sina_says_chra(y.x - x.x) + sina_says_chra(y.y - x.y) + y.d <= x.d) { mark[j] = 1; break; } } for (int j = v[i].size() - 1; ~j; j--) if (mark[j]) swap(v[i][j], v[i].back()), v[i].pop_back(); } cout << v[p].back().d << '\n'; return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class T, class L> bool smax(T &x, L y) { return x < y ? (x = y, 1) : 0; } template <class T, class L> bool smin(T &x, L y) { return y < x ? (x = y, 1) : 0; } const int maxn = 3e2 + 17, maxp = maxn * maxn, inf = 2e9; struct st { int x, y, d; }; inline int sina_says_chra(const int &x) { return x >= 0 ? x : -x; } int n, p, m; vector<st> v[maxp]; bool mark[maxp]; int main() { ios::sync_with_stdio(0), cin.tie(0); v[0].push_back({0, 0, 0}); cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0, x; j < m; j++) cin >> x, v[x].push_back({i, j, inf}); for (int i = 1; i <= p; i++) { for (auto &x : v[i]) for (auto &y : v[i - 1]) smin(x.d, y.d + sina_says_chra(y.x - x.x) + sina_says_chra(y.y - x.y)); for (int j = 0; j < v[i].size(); j++) { mark[j] = 0; st &x = v[i][j]; for (auto &y : v[i]) if ((x.x != y.x || x.y != y.y) && sina_says_chra(y.x - x.x) + sina_says_chra(y.y - x.y) + y.d <= x.d) { mark[j] = 1; break; } } for (int j = v[i].size() - 1; ~j; j--) if (mark[j]) swap(v[i][j], v[i].back()), v[i].pop_back(); } cout << v[p].back().d << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; using Point = pair<int, int>; template <typename T> using Matrix = vector<vector<T>>; const array<Point, 4> directions = {{{-1, 0}, {0, 1}, {1, 0}, {0, -1}}}; void bfs(int R, int C, const vector<Point>& source, const vector<Point>& target, Matrix<int>& global_distance) { vector<pair<int, Point>> sorted; for (const auto& p : source) { int r, c; tie(r, c) = p; sorted.push_back({global_distance[r][c], p}); } sort(begin(sorted), end(sorted)); Matrix<int> distance(R, vector<int>(C, INT_MAX)); deque<pair<int, Point>> q = {sorted[0]}; int i = 1; while (!q.empty()) { int d; Point p; tie(d, p) = q.front(); q.pop_front(); int r, c; tie(r, c) = p; if (distance[r][c] <= d) continue; else distance[r][c] = d; for (; i < sorted.size(); i++) { int nd; Point np; tie(nd, np) = sorted[i]; if (nd != d) break; q.push_front({nd, np}); } for (const auto& dir : directions) { int dr, dc; tie(dr, dc) = dir; int nr = r + dr, nc = c + dc; if (!(0 <= nr && nr < R && 0 <= nc && nc < C)) continue; q.push_back({d + 1, {nr, nc}}); } } for (const auto& p : target) { int r, c; tie(r, c) = p; global_distance[r][c] = distance[r][c]; } } void dag(const vector<Point>& source, const vector<Point>& target, Matrix<int>& distance) { for (const auto& p : source) for (const auto& q : target) { int r, c; tie(r, c) = p; int nr, nc; tie(nr, nc) = q; distance[nr][nc] = min(distance[nr][nc], distance[r][c] + abs(nr - r) + abs(nc - c)); } } int solve(int R, int C, int P, Matrix<int> A) { vector<vector<Point>> rank(P); for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) rank[A[r][c]].push_back({r, c}); Matrix<int> distance(R, vector<int>(C, INT_MAX)); for (const auto& p : rank[0]) { int r, c; tie(r, c) = p; distance[r][c] = r + c; } for (int level = 0; level + 1 < P; level++) { int a = rank[level].size(); int b = rank[level + 1].size(); if (a * a > R * C || b * b > R * C) bfs(R, C, rank[level], rank[level + 1], distance); else dag(rank[level], rank[level + 1], distance); } int r, c; tie(r, c) = rank[P - 1][0]; return distance[r][c]; } int main() { int R, C, P; cin >> R >> C >> P; Matrix<int> A(R, vector<int>(C)); for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) { cin >> A[r][c]; A[r][c]--; } cout << solve(R, C, P, move(A)) << endl; vector<int> v; return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; using Point = pair<int, int>; template <typename T> using Matrix = vector<vector<T>>; const array<Point, 4> directions = {{{-1, 0}, {0, 1}, {1, 0}, {0, -1}}}; void bfs(int R, int C, const vector<Point>& source, const vector<Point>& target, Matrix<int>& global_distance) { vector<pair<int, Point>> sorted; for (const auto& p : source) { int r, c; tie(r, c) = p; sorted.push_back({global_distance[r][c], p}); } sort(begin(sorted), end(sorted)); Matrix<int> distance(R, vector<int>(C, INT_MAX)); deque<pair<int, Point>> q = {sorted[0]}; int i = 1; while (!q.empty()) { int d; Point p; tie(d, p) = q.front(); q.pop_front(); int r, c; tie(r, c) = p; if (distance[r][c] <= d) continue; else distance[r][c] = d; for (; i < sorted.size(); i++) { int nd; Point np; tie(nd, np) = sorted[i]; if (nd != d) break; q.push_front({nd, np}); } for (const auto& dir : directions) { int dr, dc; tie(dr, dc) = dir; int nr = r + dr, nc = c + dc; if (!(0 <= nr && nr < R && 0 <= nc && nc < C)) continue; q.push_back({d + 1, {nr, nc}}); } } for (const auto& p : target) { int r, c; tie(r, c) = p; global_distance[r][c] = distance[r][c]; } } void dag(const vector<Point>& source, const vector<Point>& target, Matrix<int>& distance) { for (const auto& p : source) for (const auto& q : target) { int r, c; tie(r, c) = p; int nr, nc; tie(nr, nc) = q; distance[nr][nc] = min(distance[nr][nc], distance[r][c] + abs(nr - r) + abs(nc - c)); } } int solve(int R, int C, int P, Matrix<int> A) { vector<vector<Point>> rank(P); for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) rank[A[r][c]].push_back({r, c}); Matrix<int> distance(R, vector<int>(C, INT_MAX)); for (const auto& p : rank[0]) { int r, c; tie(r, c) = p; distance[r][c] = r + c; } for (int level = 0; level + 1 < P; level++) { int a = rank[level].size(); int b = rank[level + 1].size(); if (a * a > R * C || b * b > R * C) bfs(R, C, rank[level], rank[level + 1], distance); else dag(rank[level], rank[level + 1], distance); } int r, c; tie(r, c) = rank[P - 1][0]; return distance[r][c]; } int main() { int R, C, P; cin >> R >> C >> P; Matrix<int> A(R, vector<int>(C)); for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) { cin >> A[r][c]; A[r][c]--; } cout << solve(R, C, P, move(A)) << endl; vector<int> v; return 0; } ```
#include <bits/stdc++.h> using namespace std; class Point { public: int route; short int x, y; Point(int _r, short int _x, short int _y) { route = _r; x = _x, y = _y; } }; bool comp(const Point &a, const Point &b) { return a.route < b.route || a.route == b.route && a.x < b.x || a.route == b.route && a.x == b.x && a.y < b.y; } inline int abs(int a) { return a < 0 ? -a : a; } inline int dist(pair<short int, short int> from, pair<short int, short int> to) { return abs(from.first - to.first) + abs(from.second - to.second); } int Checked[300][300]; int main() { short int n, m; int p; scanf("%hi%hi%i", &n, &m, &p); list<pair<short int, short int> > List[90000]; int Ans[300][300]; for (short int i = 0; i < n; i++) for (short int j = 0; j < m; j++) { int a; scanf("%i", &a); List[a - 1].push_back(make_pair(i, j)); } for (auto it : List[0]) Ans[it.first][it.second] = it.first + it.second; for (int i = 1; i < p; i++) { if (List[i].size() * List[i - 1].size() <= n * m) { for (auto it2 : List[i]) { Ans[it2.first][it2.second] = dist(*List[i - 1].begin(), it2) + Ans[List[i - 1].begin()->first][List[i - 1].begin()->second]; for (auto it1 : List[i - 1]) { if (Ans[it2.first][it2.second] > dist(it1, it2) + Ans[it1.first][it1.second]) { Ans[it2.first][it2.second] = dist(it1, it2) + Ans[it1.first][it1.second]; } } } } else { queue<Point> Queue; vector<Point> Sources; for (auto it : List[i - 1]) { Sources.push_back(Point(Ans[it.first][it.second], it.first, it.second)); } sort(Sources.begin(), Sources.end(), comp); int curSrc = 1, locWave = Sources[0].route; Queue.push(Sources[0]); Checked[Sources[0].x][Sources[0].y] = i; while (curSrc < Sources.size() && Sources[curSrc].route == locWave) { Queue.push(Sources[curSrc]); Checked[Sources[curSrc].x][Sources[curSrc].y] = i; curSrc++; } while (!Queue.empty()) { Point cur = Queue.front(); Queue.pop(); locWave = cur.route + 1; if (cur.x && Checked[cur.x - 1][cur.y] != i) { Queue.push(Point(locWave, cur.x - 1, cur.y)); Checked[cur.x - 1][cur.y] = i; Ans[cur.x - 1][cur.y] = locWave; } if (cur.y && Checked[cur.x][cur.y - 1] != i) { Queue.push(Point(locWave, cur.x, cur.y - 1)); Checked[cur.x][cur.y - 1] = i; Ans[cur.x][cur.y - 1] = locWave; } if (cur.x < n - 1 && Checked[cur.x + 1][cur.y] != i) { Queue.push(Point(locWave, cur.x + 1, cur.y)); Checked[cur.x + 1][cur.y] = i; Ans[cur.x + 1][cur.y] = locWave; } if (cur.y < m - 1 && Checked[cur.x][cur.y + 1] != i) { Queue.push(Point(locWave, cur.x, cur.y + 1)); Checked[cur.x][cur.y + 1] = i; Ans[cur.x][cur.y + 1] = locWave; } while (curSrc < Sources.size() && Sources[curSrc].route == locWave) { if (Checked[Sources[curSrc].x][Sources[curSrc].y] != i) { Queue.push(Sources[curSrc]); Checked[Sources[curSrc].x][Sources[curSrc].y] = i; } curSrc++; } } } } printf("%i", Ans[List[p - 1].begin()->first][List[p - 1].begin()->second]); }
### Prompt Construct a CPP code solution to the problem outlined: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; class Point { public: int route; short int x, y; Point(int _r, short int _x, short int _y) { route = _r; x = _x, y = _y; } }; bool comp(const Point &a, const Point &b) { return a.route < b.route || a.route == b.route && a.x < b.x || a.route == b.route && a.x == b.x && a.y < b.y; } inline int abs(int a) { return a < 0 ? -a : a; } inline int dist(pair<short int, short int> from, pair<short int, short int> to) { return abs(from.first - to.first) + abs(from.second - to.second); } int Checked[300][300]; int main() { short int n, m; int p; scanf("%hi%hi%i", &n, &m, &p); list<pair<short int, short int> > List[90000]; int Ans[300][300]; for (short int i = 0; i < n; i++) for (short int j = 0; j < m; j++) { int a; scanf("%i", &a); List[a - 1].push_back(make_pair(i, j)); } for (auto it : List[0]) Ans[it.first][it.second] = it.first + it.second; for (int i = 1; i < p; i++) { if (List[i].size() * List[i - 1].size() <= n * m) { for (auto it2 : List[i]) { Ans[it2.first][it2.second] = dist(*List[i - 1].begin(), it2) + Ans[List[i - 1].begin()->first][List[i - 1].begin()->second]; for (auto it1 : List[i - 1]) { if (Ans[it2.first][it2.second] > dist(it1, it2) + Ans[it1.first][it1.second]) { Ans[it2.first][it2.second] = dist(it1, it2) + Ans[it1.first][it1.second]; } } } } else { queue<Point> Queue; vector<Point> Sources; for (auto it : List[i - 1]) { Sources.push_back(Point(Ans[it.first][it.second], it.first, it.second)); } sort(Sources.begin(), Sources.end(), comp); int curSrc = 1, locWave = Sources[0].route; Queue.push(Sources[0]); Checked[Sources[0].x][Sources[0].y] = i; while (curSrc < Sources.size() && Sources[curSrc].route == locWave) { Queue.push(Sources[curSrc]); Checked[Sources[curSrc].x][Sources[curSrc].y] = i; curSrc++; } while (!Queue.empty()) { Point cur = Queue.front(); Queue.pop(); locWave = cur.route + 1; if (cur.x && Checked[cur.x - 1][cur.y] != i) { Queue.push(Point(locWave, cur.x - 1, cur.y)); Checked[cur.x - 1][cur.y] = i; Ans[cur.x - 1][cur.y] = locWave; } if (cur.y && Checked[cur.x][cur.y - 1] != i) { Queue.push(Point(locWave, cur.x, cur.y - 1)); Checked[cur.x][cur.y - 1] = i; Ans[cur.x][cur.y - 1] = locWave; } if (cur.x < n - 1 && Checked[cur.x + 1][cur.y] != i) { Queue.push(Point(locWave, cur.x + 1, cur.y)); Checked[cur.x + 1][cur.y] = i; Ans[cur.x + 1][cur.y] = locWave; } if (cur.y < m - 1 && Checked[cur.x][cur.y + 1] != i) { Queue.push(Point(locWave, cur.x, cur.y + 1)); Checked[cur.x][cur.y + 1] = i; Ans[cur.x][cur.y + 1] = locWave; } while (curSrc < Sources.size() && Sources[curSrc].route == locWave) { if (Checked[Sources[curSrc].x][Sources[curSrc].y] != i) { Queue.push(Sources[curSrc]); Checked[Sources[curSrc].x][Sources[curSrc].y] = i; } curSrc++; } } } } printf("%i", Ans[List[p - 1].begin()->first][List[p - 1].begin()->second]); } ```
#include <bits/stdc++.h> using namespace std; int n, m, p; int A[310][310]; int C[310][310]; int d[310][310]; list<pair<int, int> > L[300 * 300 + 100]; int Dist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(b.second - a.second); } class comp { public: bool operator()(const pair<int, int>& a, const pair<int, int>& b) { return C[a.first][a.second] > C[b.first][b.second]; } }; int main() { ios_base::sync_with_stdio(0); cin >> n >> m >> p; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { cin >> A[i][j]; L[A[i][j]].push_back(pair<int, int>(i, j)); } for (auto it = L[1].begin(); it != L[1].end(); ++it) d[(*it).first][(*it).second] = (*it).second + (*it).first - 2; for (int i = 2; i <= p; ++i) { if (sqrt(L[i].size()) * sqrt(L[i - 1].size()) < 4 * sqrt(m * n)) for (auto it = L[i].begin(); it != L[i].end(); ++it) { int& Di = d[(*it).first][(*it).second]; Di = 1000000000; { for (auto it2 = L[i - 1].begin(); it2 != L[i - 1].end(); ++it2) Di = min(Di, d[(*it2).first][(*it2).second] + Dist(*it, *it2)); } } else { for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) C[i][j] = -1; priority_queue<pair<int, int>, vector<pair<int, int> >, comp> Pq; for (auto it = L[i - 1].begin(); it != L[i - 1].end(); ++it) { C[(*it).first][(*it).second] = d[(*it).first][(*it).second]; Pq.push(*it); } while (!Pq.empty()) { pair<int, int> c = Pq.top(); Pq.pop(); if (C[c.first + -1][c.second + 0] == -1) { C[c.first + -1][c.second + 0] = C[c.first][c.second] + 1; Pq.push(pair<int, int>(c.first + -1, c.second + 0)); }; if (C[c.first + 1][c.second + 0] == -1) { C[c.first + 1][c.second + 0] = C[c.first][c.second] + 1; Pq.push(pair<int, int>(c.first + 1, c.second + 0)); }; if (C[c.first + 0][c.second + 1] == -1) { C[c.first + 0][c.second + 1] = C[c.first][c.second] + 1; Pq.push(pair<int, int>(c.first + 0, c.second + 1)); }; if (C[c.first + 0][c.second + -1] == -1) { C[c.first + 0][c.second + -1] = C[c.first][c.second] + 1; Pq.push(pair<int, int>(c.first + 0, c.second + -1)); }; } for (auto it = L[i].begin(); it != L[i].end(); ++it) d[(*it).first][(*it).second] = C[(*it).first][(*it).second]; } } int x = L[p].front().first; int y = L[p].front().second; cout << d[x][y] << endl; }
### Prompt Create a solution in CPP for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, p; int A[310][310]; int C[310][310]; int d[310][310]; list<pair<int, int> > L[300 * 300 + 100]; int Dist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(b.second - a.second); } class comp { public: bool operator()(const pair<int, int>& a, const pair<int, int>& b) { return C[a.first][a.second] > C[b.first][b.second]; } }; int main() { ios_base::sync_with_stdio(0); cin >> n >> m >> p; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { cin >> A[i][j]; L[A[i][j]].push_back(pair<int, int>(i, j)); } for (auto it = L[1].begin(); it != L[1].end(); ++it) d[(*it).first][(*it).second] = (*it).second + (*it).first - 2; for (int i = 2; i <= p; ++i) { if (sqrt(L[i].size()) * sqrt(L[i - 1].size()) < 4 * sqrt(m * n)) for (auto it = L[i].begin(); it != L[i].end(); ++it) { int& Di = d[(*it).first][(*it).second]; Di = 1000000000; { for (auto it2 = L[i - 1].begin(); it2 != L[i - 1].end(); ++it2) Di = min(Di, d[(*it2).first][(*it2).second] + Dist(*it, *it2)); } } else { for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) C[i][j] = -1; priority_queue<pair<int, int>, vector<pair<int, int> >, comp> Pq; for (auto it = L[i - 1].begin(); it != L[i - 1].end(); ++it) { C[(*it).first][(*it).second] = d[(*it).first][(*it).second]; Pq.push(*it); } while (!Pq.empty()) { pair<int, int> c = Pq.top(); Pq.pop(); if (C[c.first + -1][c.second + 0] == -1) { C[c.first + -1][c.second + 0] = C[c.first][c.second] + 1; Pq.push(pair<int, int>(c.first + -1, c.second + 0)); }; if (C[c.first + 1][c.second + 0] == -1) { C[c.first + 1][c.second + 0] = C[c.first][c.second] + 1; Pq.push(pair<int, int>(c.first + 1, c.second + 0)); }; if (C[c.first + 0][c.second + 1] == -1) { C[c.first + 0][c.second + 1] = C[c.first][c.second] + 1; Pq.push(pair<int, int>(c.first + 0, c.second + 1)); }; if (C[c.first + 0][c.second + -1] == -1) { C[c.first + 0][c.second + -1] = C[c.first][c.second] + 1; Pq.push(pair<int, int>(c.first + 0, c.second + -1)); }; } for (auto it = L[i].begin(); it != L[i].end(); ++it) d[(*it).first][(*it).second] = C[(*it).first][(*it).second]; } } int x = L[p].front().first; int y = L[p].front().second; cout << d[x][y] << endl; } ```
#include <bits/stdc++.h> int n, m, k, mp[305][305]; std::vector<std::pair<int, int> > garden[90005]; int dis[305][305], dis2[305][305]; bool vis[305][305]; int dist(std::pair<int, int> a, std::pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } void refresh(int lev) { for (int i = 0; i < garden[lev].size(); ++i) { int ux = garden[lev][i].first, uy = garden[lev][i].second; for (int j = 0; j < garden[lev + 1].size(); ++j) { int vx = garden[lev + 1][j].first, vy = garden[lev + 1][j].second; dis[vx][vy] = std::min( dis[vx][vy], dis[ux][uy] + dist(garden[lev][i], garden[lev + 1][j])); } } } const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; void bfs(int lev) { memset(dis2, 0x3f, sizeof(dis2)); static std::queue<int> qx, qy; for (int i = 0; i < garden[lev].size(); ++i) { int ux = garden[lev][i].first, uy = garden[lev][i].second; dis2[ux][uy] = dis[ux][uy]; qx.push(ux); qy.push(uy); vis[ux][uy] = 1; } while (!qx.empty()) { int ux = qx.front(), uy = qy.front(); qx.pop(); qy.pop(); vis[ux][uy] = 0; for (int i = 0; i < 4; ++i) { int vx = ux + dx[i], vy = uy + dy[i]; if (vx < 0 || vx >= n || vy < 0 || vy >= m) continue; if (dis2[vx][vy] > dis2[ux][uy] + 1) { dis2[vx][vy] = dis2[ux][uy] + 1; if (!vis[vx][vy]) { qx.push(vx); qy.push(vy); vis[vx][vy] = 1; } } } } for (int i = 0; i < garden[lev + 1].size(); ++i) { int ux = garden[lev + 1][i].first, uy = garden[lev + 1][i].second; dis[ux][uy] = dis2[ux][uy]; } } void calc() { for (int i = 0; i < garden[1].size(); ++i) { int ux = garden[1][i].first, uy = garden[1][i].second; dis[ux][uy] = dist(garden[1][i], std::pair<int, int>(0, 0)); } for (int lev = 1; lev < k; ++lev) { if (garden[lev].size() * garden[lev + 1].size() < n * m) { refresh(lev); } else { bfs(lev); } } } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { scanf("%d", &mp[i][j]); garden[mp[i][j]].push_back(std::pair<int, int>(i, j)); } } memset(dis, 0x3f, sizeof(dis)); calc(); int res = 0x3f3f3f3f; for (int i = 0; i < garden[k].size(); ++i) { int ux = garden[k][i].first, uy = garden[k][i].second; res = std::min(res, dis[ux][uy]); } printf("%d", res); }
### Prompt Generate a cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> int n, m, k, mp[305][305]; std::vector<std::pair<int, int> > garden[90005]; int dis[305][305], dis2[305][305]; bool vis[305][305]; int dist(std::pair<int, int> a, std::pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } void refresh(int lev) { for (int i = 0; i < garden[lev].size(); ++i) { int ux = garden[lev][i].first, uy = garden[lev][i].second; for (int j = 0; j < garden[lev + 1].size(); ++j) { int vx = garden[lev + 1][j].first, vy = garden[lev + 1][j].second; dis[vx][vy] = std::min( dis[vx][vy], dis[ux][uy] + dist(garden[lev][i], garden[lev + 1][j])); } } } const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; void bfs(int lev) { memset(dis2, 0x3f, sizeof(dis2)); static std::queue<int> qx, qy; for (int i = 0; i < garden[lev].size(); ++i) { int ux = garden[lev][i].first, uy = garden[lev][i].second; dis2[ux][uy] = dis[ux][uy]; qx.push(ux); qy.push(uy); vis[ux][uy] = 1; } while (!qx.empty()) { int ux = qx.front(), uy = qy.front(); qx.pop(); qy.pop(); vis[ux][uy] = 0; for (int i = 0; i < 4; ++i) { int vx = ux + dx[i], vy = uy + dy[i]; if (vx < 0 || vx >= n || vy < 0 || vy >= m) continue; if (dis2[vx][vy] > dis2[ux][uy] + 1) { dis2[vx][vy] = dis2[ux][uy] + 1; if (!vis[vx][vy]) { qx.push(vx); qy.push(vy); vis[vx][vy] = 1; } } } } for (int i = 0; i < garden[lev + 1].size(); ++i) { int ux = garden[lev + 1][i].first, uy = garden[lev + 1][i].second; dis[ux][uy] = dis2[ux][uy]; } } void calc() { for (int i = 0; i < garden[1].size(); ++i) { int ux = garden[1][i].first, uy = garden[1][i].second; dis[ux][uy] = dist(garden[1][i], std::pair<int, int>(0, 0)); } for (int lev = 1; lev < k; ++lev) { if (garden[lev].size() * garden[lev + 1].size() < n * m) { refresh(lev); } else { bfs(lev); } } } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { scanf("%d", &mp[i][j]); garden[mp[i][j]].push_back(std::pair<int, int>(i, j)); } } memset(dis, 0x3f, sizeof(dis)); calc(); int res = 0x3f3f3f3f; for (int i = 0; i < garden[k].size(); ++i) { int ux = garden[k][i].first, uy = garden[k][i].second; res = std::min(res, dis[ux][uy]); } printf("%d", res); } ```
#include <bits/stdc++.h> using namespace std; int m, n, p; int grid[305][305]; int visit[305][305]; queue<pair<pair<int, int>, int> > q; struct node { int x, y, val; node(int x1, int x2, int x3) { x = x1; y = x2; val = x3; } node() {} }; vector<node> v[90005]; int dirx[4] = {0, 1, 0, -1}; int diry[4] = {1, 0, -1, 0}; void bfs(int now) { memset(visit, 0, sizeof(visit)); for (int i = 0; i < v[now].size(); i++) { visit[v[now][i].x][v[now][i].y] = v[now][i].val; q.push(make_pair(make_pair(v[now][i].x, v[now][i].y), v[now][i].val)); } while (!q.empty()) { int topx = q.front().first.first; int topy = q.front().first.second; int topz = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (abs(dirx[i] + diry[j]) != 1) continue; int nowx = topx + dirx[i]; int nowy = topy + diry[j]; if (nowx >= 1 && nowx <= n && nowy >= 1 && nowy <= m && (visit[nowx][nowy] == 0 || (visit[nowx][nowy] != 0 && visit[nowx][nowy] > topz + 1))) { visit[nowx][nowy] = topz + 1; q.push(make_pair(make_pair(nowx, nowy), topz + 1)); } } } } for (int i = 0; i < v[now + 1].size(); i++) { v[now + 1][i].val = visit[v[now + 1][i].x][v[now + 1][i].y]; } return; } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> grid[i][j]; v[grid[i][j]].push_back(node(i, j, 0)); } } for (int i = 0; i < v[1].size(); i++) { v[1][i].val = v[1][i].x - 1 + v[1][i].y - 1; } for (int i = 1; i < p; i++) { if (v[i].size() * v[i + 1].size() >= m * n) { bfs(i); continue; } for (int j = 0; j < v[i].size(); j++) { for (int k = 0; k < v[i + 1].size(); k++) { if (v[i + 1][k].val == 0) v[i + 1][k].val = v[i][j].val + abs(v[i + 1][k].x - v[i][j].x) + abs(v[i + 1][k].y - v[i][j].y); v[i + 1][k].val = min(v[i + 1][k].val, v[i][j].val + abs(v[i + 1][k].x - v[i][j].x) + abs(v[i + 1][k].y - v[i][j].y)); } } } cout << v[p][0].val; }
### Prompt Develop a solution in Cpp to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int m, n, p; int grid[305][305]; int visit[305][305]; queue<pair<pair<int, int>, int> > q; struct node { int x, y, val; node(int x1, int x2, int x3) { x = x1; y = x2; val = x3; } node() {} }; vector<node> v[90005]; int dirx[4] = {0, 1, 0, -1}; int diry[4] = {1, 0, -1, 0}; void bfs(int now) { memset(visit, 0, sizeof(visit)); for (int i = 0; i < v[now].size(); i++) { visit[v[now][i].x][v[now][i].y] = v[now][i].val; q.push(make_pair(make_pair(v[now][i].x, v[now][i].y), v[now][i].val)); } while (!q.empty()) { int topx = q.front().first.first; int topy = q.front().first.second; int topz = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (abs(dirx[i] + diry[j]) != 1) continue; int nowx = topx + dirx[i]; int nowy = topy + diry[j]; if (nowx >= 1 && nowx <= n && nowy >= 1 && nowy <= m && (visit[nowx][nowy] == 0 || (visit[nowx][nowy] != 0 && visit[nowx][nowy] > topz + 1))) { visit[nowx][nowy] = topz + 1; q.push(make_pair(make_pair(nowx, nowy), topz + 1)); } } } } for (int i = 0; i < v[now + 1].size(); i++) { v[now + 1][i].val = visit[v[now + 1][i].x][v[now + 1][i].y]; } return; } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> grid[i][j]; v[grid[i][j]].push_back(node(i, j, 0)); } } for (int i = 0; i < v[1].size(); i++) { v[1][i].val = v[1][i].x - 1 + v[1][i].y - 1; } for (int i = 1; i < p; i++) { if (v[i].size() * v[i + 1].size() >= m * n) { bfs(i); continue; } for (int j = 0; j < v[i].size(); j++) { for (int k = 0; k < v[i + 1].size(); k++) { if (v[i + 1][k].val == 0) v[i + 1][k].val = v[i][j].val + abs(v[i + 1][k].x - v[i][j].x) + abs(v[i + 1][k].y - v[i][j].y); v[i + 1][k].val = min(v[i + 1][k].val, v[i][j].val + abs(v[i + 1][k].x - v[i][j].x) + abs(v[i + 1][k].y - v[i][j].y)); } } } cout << v[p][0].val; } ```
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f7f7f7f; const int MAXN = 305; const double eps = 1e-10; int maze[MAXN][MAXN]; int dis[2][MAXN * MAXN]; int n, m, p; struct node { int x, y, len, id; node(int x = 0, int y = 0, int len = 0, int id = 0) : x(x), y(y), len(len), id(id) {} }; vector<node> g[MAXN * MAXN]; bool cmp(node X, node Y) { return X.len < Y.len; } int ABS(int x) { return x < 0 ? -x : x; } int getdis(int x1, int y1, int x2, int y2) { return ABS(x1 - x2) + ABS(y1 - y2); } int getdis(node tx, node ty) { return ABS(tx.x - ty.x) + ABS(tx.y - ty.y); } int main() { int i, j, k, now; while (scanf("%d%d%d", &n, &m, &p) != EOF) { for (i = 0; i <= p; i++) g[i].clear(); for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { scanf("%d", &maze[i][j]); g[maze[i][j]].push_back(node(i, j, INF)); } } g[0].push_back(node(1, 1)); for (i = 1; i <= p; i++) { int sz1 = g[i - 1].size(); int sz2 = g[i].size(); node tx, ty; now = 1 - now; for (j = 0; j < sz1 && j <= 1000; j++) { tx = g[i - 1][j]; for (k = 0; k < sz2; k++) { ty = g[i][k]; g[i][k].len = min(ty.len, tx.len + getdis(tx, ty)); } } sort(g[i].begin(), g[i].end(), cmp); } int ans = INF; int sz = g[p].size(); for (i = 0; i < sz; i++) { ans = min(ans, g[p][i].len); } printf("%d\n", ans); } return 0; }
### Prompt Construct a CPP code solution to the problem outlined: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = 0x3f7f7f7f; const int MAXN = 305; const double eps = 1e-10; int maze[MAXN][MAXN]; int dis[2][MAXN * MAXN]; int n, m, p; struct node { int x, y, len, id; node(int x = 0, int y = 0, int len = 0, int id = 0) : x(x), y(y), len(len), id(id) {} }; vector<node> g[MAXN * MAXN]; bool cmp(node X, node Y) { return X.len < Y.len; } int ABS(int x) { return x < 0 ? -x : x; } int getdis(int x1, int y1, int x2, int y2) { return ABS(x1 - x2) + ABS(y1 - y2); } int getdis(node tx, node ty) { return ABS(tx.x - ty.x) + ABS(tx.y - ty.y); } int main() { int i, j, k, now; while (scanf("%d%d%d", &n, &m, &p) != EOF) { for (i = 0; i <= p; i++) g[i].clear(); for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { scanf("%d", &maze[i][j]); g[maze[i][j]].push_back(node(i, j, INF)); } } g[0].push_back(node(1, 1)); for (i = 1; i <= p; i++) { int sz1 = g[i - 1].size(); int sz2 = g[i].size(); node tx, ty; now = 1 - now; for (j = 0; j < sz1 && j <= 1000; j++) { tx = g[i - 1][j]; for (k = 0; k < sz2; k++) { ty = g[i][k]; g[i][k].len = min(ty.len, tx.len + getdis(tx, ty)); } } sort(g[i].begin(), g[i].end(), cmp); } int ans = INF; int sz = g[p].size(); for (i = 0; i < sz; i++) { ans = min(ans, g[p][i].len); } printf("%d\n", ans); } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 10; const int N = 305; const int M = 1e9 + 7; int n, m, k, p; int d[N][N]; vector<vector<pair<int, int>>> vec; vector<pair<int, int>> dist[3][N]; inline int getDIST(int x, int y, int xx, int yy) { return abs(x - xx) + abs(y - yy); } int main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> d[i][j]; vec.resize(p + 1); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) vec[d[i][j]].push_back(make_pair(i, j)); for (int i = 0; i < vec[1].size(); i++) { int x = vec[1][i].first; int y = vec[1][i].second; int d = getDIST(1, 1, x, y); dist[1][y].push_back({d, x}); } int t = 1; int nt = 2; for (int i = 2; i <= p; i++) { for (int j = 1; j <= m; j++) sort(dist[t][j].begin(), dist[t][j].end()); for (int j = 1; j <= m; j++) dist[nt][j].clear(); for (int h = 0; h < vec[i].size(); h++) { int x = vec[i][h].first; int y = vec[i][h].second; int w = INF; for (int j = 1; j <= m; j++) { int k = 0; int dy = abs(j - y); while (k < dist[t][j].size() && w > dist[t][j][k].first + dy) { w = min(w, dist[t][j][k].first + abs(dist[t][j][k].second - x) + dy); k++; } } dist[nt][y].push_back({w, x}); } swap(t, nt); } int ans = INF; for (int i = 1; i <= m; i++) for (int j = 0; j < dist[t][i].size(); j++) ans = min(ans, dist[t][i][j].first); cout << ans; return 0; }
### Prompt Develop a solution in Cpp to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 10; const int N = 305; const int M = 1e9 + 7; int n, m, k, p; int d[N][N]; vector<vector<pair<int, int>>> vec; vector<pair<int, int>> dist[3][N]; inline int getDIST(int x, int y, int xx, int yy) { return abs(x - xx) + abs(y - yy); } int main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> d[i][j]; vec.resize(p + 1); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) vec[d[i][j]].push_back(make_pair(i, j)); for (int i = 0; i < vec[1].size(); i++) { int x = vec[1][i].first; int y = vec[1][i].second; int d = getDIST(1, 1, x, y); dist[1][y].push_back({d, x}); } int t = 1; int nt = 2; for (int i = 2; i <= p; i++) { for (int j = 1; j <= m; j++) sort(dist[t][j].begin(), dist[t][j].end()); for (int j = 1; j <= m; j++) dist[nt][j].clear(); for (int h = 0; h < vec[i].size(); h++) { int x = vec[i][h].first; int y = vec[i][h].second; int w = INF; for (int j = 1; j <= m; j++) { int k = 0; int dy = abs(j - y); while (k < dist[t][j].size() && w > dist[t][j][k].first + dy) { w = min(w, dist[t][j][k].first + abs(dist[t][j][k].second - x) + dy); k++; } } dist[nt][y].push_back({w, x}); } swap(t, nt); } int ans = INF; for (int i = 1; i <= m; i++) for (int j = 0; j < dist[t][i].size(); j++) ans = min(ans, dist[t][i][j].first); cout << ans; return 0; } ```
#include <bits/stdc++.h> const int N = 300; const int M = 3e6; const int inf = 1e9; using namespace std; int n, m, p, a[N + 5][N + 5], dis[N + 5][N + 5], id[N + 5][N + 5], idc, q[N * N + 5], dd[N + 5][N + 5], c[N * N + 5], cnt, X[N * N + 5], Y[N * N + 5]; int dx[5] = {0, 1, -1, 0, 0}, dy[5] = {0, 0, 0, 1, -1}; vector<pair<int, int> > d[N * N + 5]; vector<pair<int, int> >::iterator it1, it2; int myabs(int x) { return x < 0 ? -x : x; } int dist(int u, int v, int x, int y) { return myabs(v - y) + myabs(x - u); } bool cmp(int x, int y) { return dis[X[x]][Y[x]] < dis[X[y]][Y[y]]; } void bfs(int x) { int l = 1, r = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) dd[i][j] = inf; cnt = 0; for (it1 = d[x].begin(); it1 != d[x].end(); it1++) c[++cnt] = id[(*it1).first][(*it1).second]; sort(c + 1, c + cnt + 1, cmp); int pos = 1; dd[X[c[pos]]][Y[c[pos]]] = dis[X[c[pos]]][Y[c[pos]]]; q[++r] = c[pos++]; while (l <= r) { int u = q[l++]; while (pos <= cnt && dis[X[c[pos]]][Y[c[pos]]] == dd[X[u]][Y[u]]) { if (dd[X[c[pos]]][Y[c[pos]]] == inf) dd[X[c[pos]]][Y[c[pos]]] = dis[X[c[pos]]][Y[c[pos]]], q[++r] = c[pos++]; else pos++; } for (int i = 1; i <= 4; i++) { int xx = X[u] + dx[i], yy = Y[u] + dy[i]; if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && dd[xx][yy] == inf) { dd[xx][yy] = dd[X[u]][Y[u]] + 1; if (a[xx][yy] == x + 1) dis[xx][yy] = dd[xx][yy]; q[++r] = id[xx][yy]; } } } } int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); d[a[i][j]].push_back(make_pair(i, j)); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { id[i][j] = ++idc; X[idc] = i; Y[idc] = j; } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == 1) dis[i][j] = i + j - 2; else dis[i][j] = inf; for (int i = 1; i < p; i++) { if (d[i].size() * d[i + 1].size() <= n * m) { for (it1 = d[i].begin(); it1 != d[i].end(); it1++) { int u = (*it1).first, v = (*it1).second; for (it2 = d[i + 1].begin(); it2 != d[i + 1].end(); it2++) { int x = (*it2).first, y = (*it2).second; dis[x][y] = min(dis[x][y], dis[u][v] + dist(u, v, x, y)); } } } else bfs(i); } cout << dis[d[p][0].first][d[p][0].second] << endl; return 0; }
### Prompt Your task is to create a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> const int N = 300; const int M = 3e6; const int inf = 1e9; using namespace std; int n, m, p, a[N + 5][N + 5], dis[N + 5][N + 5], id[N + 5][N + 5], idc, q[N * N + 5], dd[N + 5][N + 5], c[N * N + 5], cnt, X[N * N + 5], Y[N * N + 5]; int dx[5] = {0, 1, -1, 0, 0}, dy[5] = {0, 0, 0, 1, -1}; vector<pair<int, int> > d[N * N + 5]; vector<pair<int, int> >::iterator it1, it2; int myabs(int x) { return x < 0 ? -x : x; } int dist(int u, int v, int x, int y) { return myabs(v - y) + myabs(x - u); } bool cmp(int x, int y) { return dis[X[x]][Y[x]] < dis[X[y]][Y[y]]; } void bfs(int x) { int l = 1, r = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) dd[i][j] = inf; cnt = 0; for (it1 = d[x].begin(); it1 != d[x].end(); it1++) c[++cnt] = id[(*it1).first][(*it1).second]; sort(c + 1, c + cnt + 1, cmp); int pos = 1; dd[X[c[pos]]][Y[c[pos]]] = dis[X[c[pos]]][Y[c[pos]]]; q[++r] = c[pos++]; while (l <= r) { int u = q[l++]; while (pos <= cnt && dis[X[c[pos]]][Y[c[pos]]] == dd[X[u]][Y[u]]) { if (dd[X[c[pos]]][Y[c[pos]]] == inf) dd[X[c[pos]]][Y[c[pos]]] = dis[X[c[pos]]][Y[c[pos]]], q[++r] = c[pos++]; else pos++; } for (int i = 1; i <= 4; i++) { int xx = X[u] + dx[i], yy = Y[u] + dy[i]; if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && dd[xx][yy] == inf) { dd[xx][yy] = dd[X[u]][Y[u]] + 1; if (a[xx][yy] == x + 1) dis[xx][yy] = dd[xx][yy]; q[++r] = id[xx][yy]; } } } } int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); d[a[i][j]].push_back(make_pair(i, j)); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { id[i][j] = ++idc; X[idc] = i; Y[idc] = j; } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == 1) dis[i][j] = i + j - 2; else dis[i][j] = inf; for (int i = 1; i < p; i++) { if (d[i].size() * d[i + 1].size() <= n * m) { for (it1 = d[i].begin(); it1 != d[i].end(); it1++) { int u = (*it1).first, v = (*it1).second; for (it2 = d[i + 1].begin(); it2 != d[i + 1].end(); it2++) { int x = (*it2).first, y = (*it2).second; dis[x][y] = min(dis[x][y], dis[u][v] + dist(u, v, x, y)); } } } else bfs(i); } cout << dis[d[p][0].first][d[p][0].second] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; struct __s { __s() { srand(time(NULL)); if (1) { ios_base::Init i; cin.sync_with_stdio(0); cin.tie(0); } } ~__s() { if (!1) fprintf(stderr, "Execution time: %.3lf s.\n", (double)clock() / CLOCKS_PER_SEC); int n; cin >> n; } } __S; int n, m, p; int a[311][311]; vector<pair<int, int> > g[91111]; int xp, yp; int t[311][311]; int d[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; inline int dist(int &x1, int &y1, int &x2, int &y2) { return abs(x1 - x2) + abs(y1 - y2); } inline bool check(int x, int y) { return (0 <= x && x < n) && (0 <= y && y < m); } int main(void) { cin >> n >> m >> p; for (int i = 0; i < (int)(n); i++) { for (int j = 0; j < (int)(m); j++) { cin >> a[i][j]; a[i][j]--; g[a[i][j]].push_back(make_pair(i, j)); t[i][j] = 1e9; } } xp = g[p - 1][0].first; yp = g[p - 1][0].second; for (int i = 0; i < (int)(g[0].size()); i++) { int x = g[0][i].first; int y = g[0][i].second; t[x][y] = x + y; } for (int i = 1; i < p; i++) { if (1LL * g[i].size() * g[i - 1].size() >= 2e6) { priority_queue<pair<int, pair<int, int> > > q; vector<vector<int> > u(n, vector<int>(m, 1e9)); for (int j = 0; j < (int)(g[i - 1].size()); j++) { int x = g[i - 1][j].first; int y = g[i - 1][j].second; q.push(make_pair(-t[x][y], make_pair(x, y))); u[x][y] = t[x][y]; } while (q.size()) { int tt = -q.top().first; int x = q.top().second.first; int y = q.top().second.second; q.pop(); if (tt > u[x][y]) continue; if (a[x][y] == i) t[x][y] = min(t[x][y], tt); tt++; for (int j = 0; j < (int)(4); j++) { int xx = x + d[j][0]; int yy = y + d[j][1]; if (!check(xx, yy)) continue; if (tt >= u[xx][yy]) continue; q.push(make_pair(-tt, make_pair(xx, yy))); u[xx][yy] = tt; } } continue; } for (int j = 0; j < (int)(g[i].size()); j++) { int x1 = g[i][j].first; int y1 = g[i][j].second; int res = 1e9; for (int k = 0; k < (int)(g[i - 1].size()); k++) { int x2 = g[i - 1][k].first; int y2 = g[i - 1][k].second; res = min(res, t[x2][y2] + dist(x1, y1, x2, y2)); } t[x1][y1] = res; } } cout << t[xp][yp] << '\n'; return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct __s { __s() { srand(time(NULL)); if (1) { ios_base::Init i; cin.sync_with_stdio(0); cin.tie(0); } } ~__s() { if (!1) fprintf(stderr, "Execution time: %.3lf s.\n", (double)clock() / CLOCKS_PER_SEC); int n; cin >> n; } } __S; int n, m, p; int a[311][311]; vector<pair<int, int> > g[91111]; int xp, yp; int t[311][311]; int d[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; inline int dist(int &x1, int &y1, int &x2, int &y2) { return abs(x1 - x2) + abs(y1 - y2); } inline bool check(int x, int y) { return (0 <= x && x < n) && (0 <= y && y < m); } int main(void) { cin >> n >> m >> p; for (int i = 0; i < (int)(n); i++) { for (int j = 0; j < (int)(m); j++) { cin >> a[i][j]; a[i][j]--; g[a[i][j]].push_back(make_pair(i, j)); t[i][j] = 1e9; } } xp = g[p - 1][0].first; yp = g[p - 1][0].second; for (int i = 0; i < (int)(g[0].size()); i++) { int x = g[0][i].first; int y = g[0][i].second; t[x][y] = x + y; } for (int i = 1; i < p; i++) { if (1LL * g[i].size() * g[i - 1].size() >= 2e6) { priority_queue<pair<int, pair<int, int> > > q; vector<vector<int> > u(n, vector<int>(m, 1e9)); for (int j = 0; j < (int)(g[i - 1].size()); j++) { int x = g[i - 1][j].first; int y = g[i - 1][j].second; q.push(make_pair(-t[x][y], make_pair(x, y))); u[x][y] = t[x][y]; } while (q.size()) { int tt = -q.top().first; int x = q.top().second.first; int y = q.top().second.second; q.pop(); if (tt > u[x][y]) continue; if (a[x][y] == i) t[x][y] = min(t[x][y], tt); tt++; for (int j = 0; j < (int)(4); j++) { int xx = x + d[j][0]; int yy = y + d[j][1]; if (!check(xx, yy)) continue; if (tt >= u[xx][yy]) continue; q.push(make_pair(-tt, make_pair(xx, yy))); u[xx][yy] = tt; } } continue; } for (int j = 0; j < (int)(g[i].size()); j++) { int x1 = g[i][j].first; int y1 = g[i][j].second; int res = 1e9; for (int k = 0; k < (int)(g[i - 1].size()); k++) { int x2 = g[i - 1][k].first; int y2 = g[i - 1][k].second; res = min(res, t[x2][y2] + dist(x1, y1, x2, y2)); } t[x1][y1] = res; } } cout << t[xp][yp] << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > V[310 * 310]; int dx[4] = {0, -1, 0, 1}; int dy[4] = {1, 0, -1, 0}; int a[310][310]; int dp[310][310]; int dis[310][310]; int vis[310][310]; int main() { int n, m, p; cin >> n >> m >> p; memset(dp, (127), sizeof(dp)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); V[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) dp[i][j] = i - 1 + j - 1; } queue<pair<int, int> > Q; int level = sqrt(n * m); for (int i = 1; i < p; i++) { if (V[i].size() <= level) { for (int j = 0; j < V[i + 1].size(); j++) { for (int k = 0; k < V[i].size(); k++) { dp[V[i + 1][j].first][V[i + 1][j].second] = min(dp[V[i + 1][j].first][V[i + 1][j].second], dp[V[i][k].first][V[i][k].second] + abs(V[i + 1][j].first - V[i][k].first) + abs(V[i + 1][j].second - V[i][k].second)); } } } else { memset(dis, (127), sizeof(dis)); for (int j = 0; j < V[i].size(); j++) { dis[V[i][j].first][V[i][j].second] = dp[V[i][j].first][V[i][j].second]; Q.push(V[i][j]); } while (!Q.empty()) { pair<int, int> now = Q.front(); Q.pop(); pair<int, int> next; for (int k = 0; k < 4; k++) { next.first = now.first + dx[k]; next.second = now.second + dy[k]; if (next.first > n || next.first < 1) continue; if (next.second > m || next.second < 1) continue; if (dis[next.first][next.second] > dis[now.first][now.second] + 1) { dis[next.first][next.second] = dis[now.first][now.second] + 1; Q.push(next); } } } for (int j = 0; j < V[i + 1].size(); j++) { dp[V[i + 1][j].first][V[i + 1][j].second] = dis[V[i + 1][j].first][V[i + 1][j].second]; } } } printf("%d\n", dp[V[p][0].first][V[p][0].second]); return 0; }
### Prompt Develop a solution in Cpp to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<pair<int, int> > V[310 * 310]; int dx[4] = {0, -1, 0, 1}; int dy[4] = {1, 0, -1, 0}; int a[310][310]; int dp[310][310]; int dis[310][310]; int vis[310][310]; int main() { int n, m, p; cin >> n >> m >> p; memset(dp, (127), sizeof(dp)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); V[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) dp[i][j] = i - 1 + j - 1; } queue<pair<int, int> > Q; int level = sqrt(n * m); for (int i = 1; i < p; i++) { if (V[i].size() <= level) { for (int j = 0; j < V[i + 1].size(); j++) { for (int k = 0; k < V[i].size(); k++) { dp[V[i + 1][j].first][V[i + 1][j].second] = min(dp[V[i + 1][j].first][V[i + 1][j].second], dp[V[i][k].first][V[i][k].second] + abs(V[i + 1][j].first - V[i][k].first) + abs(V[i + 1][j].second - V[i][k].second)); } } } else { memset(dis, (127), sizeof(dis)); for (int j = 0; j < V[i].size(); j++) { dis[V[i][j].first][V[i][j].second] = dp[V[i][j].first][V[i][j].second]; Q.push(V[i][j]); } while (!Q.empty()) { pair<int, int> now = Q.front(); Q.pop(); pair<int, int> next; for (int k = 0; k < 4; k++) { next.first = now.first + dx[k]; next.second = now.second + dy[k]; if (next.first > n || next.first < 1) continue; if (next.second > m || next.second < 1) continue; if (dis[next.first][next.second] > dis[now.first][now.second] + 1) { dis[next.first][next.second] = dis[now.first][now.second] + 1; Q.push(next); } } } for (int j = 0; j < V[i + 1].size(); j++) { dp[V[i + 1][j].first][V[i + 1][j].second] = dis[V[i + 1][j].first][V[i + 1][j].second]; } } } printf("%d\n", dp[V[p][0].first][V[p][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 3e2; const long long INF = 4e18; int n, m, p; long long matrix[N][N], ans[N][N], bfs[N][N]; bool used[N][N]; struct Coord { int x, y; Coord() {} Coord(long long x, long long y) { this->x = x; this->y = y; } } bg(0, 0); vector<pair<int, int> > delta{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; vector<Coord> g[N * N]; long long dist(const Coord& a, const Coord& b) { return (abs(a.x - b.x) + abs(a.y - b.y)); } bool check(int x, int y) { return !(x < 0 || y < 0 || x >= n || y >= m); } queue<Coord> q; void dobfs(int color) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { used[i][j] = false; if (matrix[i][j] != color) bfs[i][j] = INF; else { bfs[i][j] = ans[i][j]; } } Coord cur; int nx, ny; while (!q.empty()) { cur = q.front(); q.pop(); for (auto d : delta) { nx = cur.x + d.first; ny = cur.y + d.second; if (check(nx, ny) && bfs[nx][ny] > bfs[cur.x][cur.y] + 1) { bfs[nx][ny] = min(bfs[nx][ny], bfs[cur.x][cur.y] + 1); q.push(Coord(nx, ny)); } } } } void solve() { cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> matrix[i][j]; g[matrix[i][j]].push_back(Coord(i, j)); if (matrix[i][j] == 1) ans[i][j] = i + j; else ans[i][j] = INF; } } int pcolor, nx, ny; for (int color = 1; color <= p; color++) { if (g[color].size() * g[color - 1].size() < n * m) { for (auto j : g[color]) { for (auto i : g[color - 1]) { ans[j.x][j.y] = min(ans[j.x][j.y], ans[i.x][i.y] + dist(i, j)); } } } else { for (auto j : g[color - 1]) q.push(j); dobfs(color - 1); for (auto j : g[color]) ans[j.x][j.y] = bfs[j.x][j.y]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) if (matrix[i][j] == p) { cout << ans[i][j]; return; } } } int main() { solve(); return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 3e2; const long long INF = 4e18; int n, m, p; long long matrix[N][N], ans[N][N], bfs[N][N]; bool used[N][N]; struct Coord { int x, y; Coord() {} Coord(long long x, long long y) { this->x = x; this->y = y; } } bg(0, 0); vector<pair<int, int> > delta{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; vector<Coord> g[N * N]; long long dist(const Coord& a, const Coord& b) { return (abs(a.x - b.x) + abs(a.y - b.y)); } bool check(int x, int y) { return !(x < 0 || y < 0 || x >= n || y >= m); } queue<Coord> q; void dobfs(int color) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { used[i][j] = false; if (matrix[i][j] != color) bfs[i][j] = INF; else { bfs[i][j] = ans[i][j]; } } Coord cur; int nx, ny; while (!q.empty()) { cur = q.front(); q.pop(); for (auto d : delta) { nx = cur.x + d.first; ny = cur.y + d.second; if (check(nx, ny) && bfs[nx][ny] > bfs[cur.x][cur.y] + 1) { bfs[nx][ny] = min(bfs[nx][ny], bfs[cur.x][cur.y] + 1); q.push(Coord(nx, ny)); } } } } void solve() { cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> matrix[i][j]; g[matrix[i][j]].push_back(Coord(i, j)); if (matrix[i][j] == 1) ans[i][j] = i + j; else ans[i][j] = INF; } } int pcolor, nx, ny; for (int color = 1; color <= p; color++) { if (g[color].size() * g[color - 1].size() < n * m) { for (auto j : g[color]) { for (auto i : g[color - 1]) { ans[j.x][j.y] = min(ans[j.x][j.y], ans[i.x][i.y] + dist(i, j)); } } } else { for (auto j : g[color - 1]) q.push(j); dobfs(color - 1); for (auto j : g[color]) ans[j.x][j.y] = bfs[j.x][j.y]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) if (matrix[i][j] == p) { cout << ans[i][j]; return; } } } int main() { solve(); return 0; } ```
#include <bits/stdc++.h> using namespace std; constexpr int INF = 87654321; class Fenwick { public: vector<int> tree; int length; int Rmq(int i) { int ret = INF; while (i) { ret = min(ret, tree[i]); i -= i & -i; } return ret; } void Update(int i, int val) { while (i <= length) { tree[i] = min(tree[i], val); i += i & -i; } } Fenwick() {} Fenwick(int length) : tree(length + 1, INF), length(length) {} void reset() { for (int i = 0; i < length + 1; ++i) tree[i] = INF; } }; int n, m, p; Fenwick fenwick[4]; vector<vector<int>> board, dp; vector<vector<pair<int, int>>> idx; vector<vector<pair<int, int>>> level[4], true_idx[4]; void Solve() { for (int x = 0; x < 4; ++x) { fenwick[x] = Fenwick(m); level[x].clear(); level[x].resize(p + 1); true_idx[x].clear(); true_idx[x].resize(p + 1); vector<pair<int, pair<pair<int, int>, pair<int, int>>>> chest; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { chest.push_back({board[i][j], {{i, j}, idx[i][j]}}); } } sort(chest.begin(), chest.end()); for (int i = 0; i < n * m; ++i) { level[x][chest[i].first].push_back(chest[i].second.first); true_idx[x][chest[i].first].push_back(chest[i].second.second); } vector<vector<int>> rotated_board(m + 1, vector<int>(n + 1, 0)); vector<vector<pair<int, int>>> rotated_idx( m + 1, vector<pair<int, int>>(n + 1, {0, 0})); for (int j = 1; j <= m; ++j) { for (int i = 1; i <= n; ++i) { rotated_board[j][i] = board[n + 1 - i][j]; rotated_idx[j][i] = idx[n + 1 - i][j]; } } board = rotated_board; idx = rotated_idx; swap(n, m); } dp = vector<vector<int>>(n + 1, vector<int>(m + 1, INF)); dp[level[0][p][0].first][level[0][p][0].second] = 0; for (int v = p - 1; v >= 1; --v) { for (int x = 0; x < 4; ++x) { auto& cur_tree = fenwick[x]; cur_tree.reset(); const auto& query = level[x][v]; const auto& data = level[x][v + 1]; const auto& query_idx = true_idx[x][v]; const auto& data_idx = true_idx[x][v + 1]; int i = 0, j = 0; while (i < query.size()) { while (j < data.size() && (data[j].first < query[i].first || (data[j].first == query[i].first && data[j].second < query[i].second))) { cur_tree.Update(data[j].second, dp[data_idx[j].first][data_idx[j].second] - data[j].first - data[j].second); ++j; } auto& val = dp[query_idx[i].first][query_idx[i].second]; val = min(val, cur_tree.Rmq(query[i].second) + query[i].first + query[i].second); ++i; } } } } int main() { scanf("%d%d%d", &n, &m, &p); board = vector<vector<int>>(n + 1, vector<int>(m + 1, 0)); idx = vector<vector<pair<int, int>>>(n + 1, vector<pair<int, int>>(m + 1, {0, 0})); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &board[i][j]); idx[i][j] = {i, j}; } } Solve(); int ans = INF; for (int i = 0; i < level[0][1].size(); ++i) { ans = min(ans, dp[level[0][1][i].first][level[0][1][i].second] + abs(level[0][1][i].first - 1) + abs(level[0][1][i].second - 1)); } printf("%d\n", ans); return 0; }
### Prompt Your task is to create a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; constexpr int INF = 87654321; class Fenwick { public: vector<int> tree; int length; int Rmq(int i) { int ret = INF; while (i) { ret = min(ret, tree[i]); i -= i & -i; } return ret; } void Update(int i, int val) { while (i <= length) { tree[i] = min(tree[i], val); i += i & -i; } } Fenwick() {} Fenwick(int length) : tree(length + 1, INF), length(length) {} void reset() { for (int i = 0; i < length + 1; ++i) tree[i] = INF; } }; int n, m, p; Fenwick fenwick[4]; vector<vector<int>> board, dp; vector<vector<pair<int, int>>> idx; vector<vector<pair<int, int>>> level[4], true_idx[4]; void Solve() { for (int x = 0; x < 4; ++x) { fenwick[x] = Fenwick(m); level[x].clear(); level[x].resize(p + 1); true_idx[x].clear(); true_idx[x].resize(p + 1); vector<pair<int, pair<pair<int, int>, pair<int, int>>>> chest; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { chest.push_back({board[i][j], {{i, j}, idx[i][j]}}); } } sort(chest.begin(), chest.end()); for (int i = 0; i < n * m; ++i) { level[x][chest[i].first].push_back(chest[i].second.first); true_idx[x][chest[i].first].push_back(chest[i].second.second); } vector<vector<int>> rotated_board(m + 1, vector<int>(n + 1, 0)); vector<vector<pair<int, int>>> rotated_idx( m + 1, vector<pair<int, int>>(n + 1, {0, 0})); for (int j = 1; j <= m; ++j) { for (int i = 1; i <= n; ++i) { rotated_board[j][i] = board[n + 1 - i][j]; rotated_idx[j][i] = idx[n + 1 - i][j]; } } board = rotated_board; idx = rotated_idx; swap(n, m); } dp = vector<vector<int>>(n + 1, vector<int>(m + 1, INF)); dp[level[0][p][0].first][level[0][p][0].second] = 0; for (int v = p - 1; v >= 1; --v) { for (int x = 0; x < 4; ++x) { auto& cur_tree = fenwick[x]; cur_tree.reset(); const auto& query = level[x][v]; const auto& data = level[x][v + 1]; const auto& query_idx = true_idx[x][v]; const auto& data_idx = true_idx[x][v + 1]; int i = 0, j = 0; while (i < query.size()) { while (j < data.size() && (data[j].first < query[i].first || (data[j].first == query[i].first && data[j].second < query[i].second))) { cur_tree.Update(data[j].second, dp[data_idx[j].first][data_idx[j].second] - data[j].first - data[j].second); ++j; } auto& val = dp[query_idx[i].first][query_idx[i].second]; val = min(val, cur_tree.Rmq(query[i].second) + query[i].first + query[i].second); ++i; } } } } int main() { scanf("%d%d%d", &n, &m, &p); board = vector<vector<int>>(n + 1, vector<int>(m + 1, 0)); idx = vector<vector<pair<int, int>>>(n + 1, vector<pair<int, int>>(m + 1, {0, 0})); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &board[i][j]); idx[i][j] = {i, j}; } } Solve(); int ans = INF; for (int i = 0; i < level[0][1].size(); ++i) { ans = min(ans, dp[level[0][1][i].first][level[0][1][i].second] + abs(level[0][1][i].first - 1) + abs(level[0][1][i].second - 1)); } printf("%d\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int fx[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; const int fxx[8][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; template <typename T, typename TT> ostream& operator<<(ostream& s, pair<T, TT> t) { return s << "(" << t.first << "," << t.second << ")"; } template <typename T> ostream& operator<<(ostream& s, vector<T> t) { s << "["; for (int i = 0; i < ((int)(t.size())) - 1; i++) s << t[i] << ", "; s << t[((int)(t.size())) - 1] << "]"; return s; } const int MOD = 1e9 + 7; template <typename T> inline T gcD(T a, T b) { if (a < b) swap(a, b); while (b) { a = a % b; b ^= a; a ^= b; b ^= a; }; return a; } template <typename T> inline T pow_mod(T a, T b) { T res = 1; while (b) { if (b & 1) res = (res * a) % MOD; a = (a * a) % MOD; b >>= 1; } return res; } struct Node { int value, x, y; bool operator<(const Node other) const { if (value == other.value && x == other.x) return y < other.y; else if (value == other.value) return x < other.x; else return value < other.value; } }; const int MAXN = 310; int room[MAXN][MAXN]; int dis[MAXN][MAXN]; vector<Node> dp[MAXN * MAXN]; vector<Node> bfs; int main() { int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> room[i][j]; if (room[i][j] == 1) { dp[1].push_back({i + j, i, j}); } else dp[room[i][j]].push_back({(int)1e9, i, j}); } for (int i = 2; i < p + 1; i++) { if (dp[i - 1].size() * dp[i].size() >= n * m) { bfs.clear(); sort(dp[i - 1].begin(), dp[i - 1].end()); bfs.push_back(dp[i - 1][0]); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) dis[i][j] = (int)1e9; dis[dp[i - 1][0].x][dp[i - 1][0].y] = dp[i - 1][0].value; int pt = 1; int j = 0; while (j < bfs.size()) { Node top = bfs[j++]; while (pt < dp[i - 1].size() && dp[i - 1][pt].value <= top.value) bfs.push_back(dp[i - 1][pt++]); for (int k = 0; k < 4; k++) { int new_x = top.x + fx[k][0]; int new_y = top.y + fx[k][1]; if (new_x >= 0 && new_x < n && new_y >= 0 && new_y < m) { if (dis[new_x][new_y] > top.value + 1) { dis[new_x][new_y] = top.value + 1; bfs.push_back({dis[new_x][new_y], new_x, new_y}); } } } } for (__typeof((dp[i]).begin()) v = (dp[i]).begin(); v != (dp[i]).end(); ++v) { v->value = dis[v->x][v->y]; } } else { for (__typeof((dp[i]).begin()) v = (dp[i]).begin(); v != (dp[i]).end(); ++v) { for (__typeof((dp[i - 1]).begin()) w = (dp[i - 1]).begin(); w != (dp[i - 1]).end(); ++w) { v->value = min(v->value, w->value + abs(w->x - v->x) + abs(w->y - v->y)); } } } } cout << dp[p][0].value << endl; return 0; }
### Prompt Construct a cpp code solution to the problem outlined: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int fx[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; const int fxx[8][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; template <typename T, typename TT> ostream& operator<<(ostream& s, pair<T, TT> t) { return s << "(" << t.first << "," << t.second << ")"; } template <typename T> ostream& operator<<(ostream& s, vector<T> t) { s << "["; for (int i = 0; i < ((int)(t.size())) - 1; i++) s << t[i] << ", "; s << t[((int)(t.size())) - 1] << "]"; return s; } const int MOD = 1e9 + 7; template <typename T> inline T gcD(T a, T b) { if (a < b) swap(a, b); while (b) { a = a % b; b ^= a; a ^= b; b ^= a; }; return a; } template <typename T> inline T pow_mod(T a, T b) { T res = 1; while (b) { if (b & 1) res = (res * a) % MOD; a = (a * a) % MOD; b >>= 1; } return res; } struct Node { int value, x, y; bool operator<(const Node other) const { if (value == other.value && x == other.x) return y < other.y; else if (value == other.value) return x < other.x; else return value < other.value; } }; const int MAXN = 310; int room[MAXN][MAXN]; int dis[MAXN][MAXN]; vector<Node> dp[MAXN * MAXN]; vector<Node> bfs; int main() { int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> room[i][j]; if (room[i][j] == 1) { dp[1].push_back({i + j, i, j}); } else dp[room[i][j]].push_back({(int)1e9, i, j}); } for (int i = 2; i < p + 1; i++) { if (dp[i - 1].size() * dp[i].size() >= n * m) { bfs.clear(); sort(dp[i - 1].begin(), dp[i - 1].end()); bfs.push_back(dp[i - 1][0]); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) dis[i][j] = (int)1e9; dis[dp[i - 1][0].x][dp[i - 1][0].y] = dp[i - 1][0].value; int pt = 1; int j = 0; while (j < bfs.size()) { Node top = bfs[j++]; while (pt < dp[i - 1].size() && dp[i - 1][pt].value <= top.value) bfs.push_back(dp[i - 1][pt++]); for (int k = 0; k < 4; k++) { int new_x = top.x + fx[k][0]; int new_y = top.y + fx[k][1]; if (new_x >= 0 && new_x < n && new_y >= 0 && new_y < m) { if (dis[new_x][new_y] > top.value + 1) { dis[new_x][new_y] = top.value + 1; bfs.push_back({dis[new_x][new_y], new_x, new_y}); } } } } for (__typeof((dp[i]).begin()) v = (dp[i]).begin(); v != (dp[i]).end(); ++v) { v->value = dis[v->x][v->y]; } } else { for (__typeof((dp[i]).begin()) v = (dp[i]).begin(); v != (dp[i]).end(); ++v) { for (__typeof((dp[i - 1]).begin()) w = (dp[i - 1]).begin(); w != (dp[i - 1]).end(); ++w) { v->value = min(v->value, w->value + abs(w->x - v->x) + abs(w->y - v->y)); } } } } cout << dp[p][0].value << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; int mat[303][303], n, m, p = 2; int dp[303][303]; vector<pair<int, int> > all[303 * 303]; vector<int> v[303]; bool vis[303]; int main() { int i, j; scanf("%d", &n); scanf("%d", &m); scanf("%d", &p); if (p == 1) return cout << 0 << endl, 0; memset(dp, 0x3f3f3f3f, sizeof(dp)); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { scanf("%d", &mat[i][j]); all[mat[i][j]].push_back({i, j}); if (mat[i][j] == 1) dp[i][j] = i + j; } } for (int a = 1; a < p; a++) { for (i = 0; i < m; i++) v[i].clear(); memset(vis, false, sizeof(vis)); for (auto xx : all[a + 1]) { int x = xx.first, y = xx.second; v[y].push_back(x); } for (auto xx : all[a]) vis[xx.first] = true; for (i = 0; i < n; i++) { if (vis[i] == false) continue; int best = 0x3f3f3f3f; for (j = 0; j < m; j++) { if (mat[i][j] == a) best = dp[i][j]; else best = min(0x3f3f3f3f, best + 1); if (best == 0x3f3f3f3f) continue; for (auto x : v[j]) { dp[x][j] = min(dp[x][j], best + abs(i - x)); } } best = 0x3f3f3f3f; for (j = m - 1; j >= 0; j--) { if (mat[i][j] == a) best = dp[i][j]; else best = min(0x3f3f3f3f, best + 1); if (best == 0x3f3f3f3f) continue; for (auto x : v[j]) { dp[x][j] = min(dp[x][j], best + abs(i - x)); } } } } for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { if (mat[i][j] == p) return cout << dp[i][j] << endl, 0; } } }
### Prompt Create a solution in cpp for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int mat[303][303], n, m, p = 2; int dp[303][303]; vector<pair<int, int> > all[303 * 303]; vector<int> v[303]; bool vis[303]; int main() { int i, j; scanf("%d", &n); scanf("%d", &m); scanf("%d", &p); if (p == 1) return cout << 0 << endl, 0; memset(dp, 0x3f3f3f3f, sizeof(dp)); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { scanf("%d", &mat[i][j]); all[mat[i][j]].push_back({i, j}); if (mat[i][j] == 1) dp[i][j] = i + j; } } for (int a = 1; a < p; a++) { for (i = 0; i < m; i++) v[i].clear(); memset(vis, false, sizeof(vis)); for (auto xx : all[a + 1]) { int x = xx.first, y = xx.second; v[y].push_back(x); } for (auto xx : all[a]) vis[xx.first] = true; for (i = 0; i < n; i++) { if (vis[i] == false) continue; int best = 0x3f3f3f3f; for (j = 0; j < m; j++) { if (mat[i][j] == a) best = dp[i][j]; else best = min(0x3f3f3f3f, best + 1); if (best == 0x3f3f3f3f) continue; for (auto x : v[j]) { dp[x][j] = min(dp[x][j], best + abs(i - x)); } } best = 0x3f3f3f3f; for (j = m - 1; j >= 0; j--) { if (mat[i][j] == a) best = dp[i][j]; else best = min(0x3f3f3f3f, best + 1); if (best == 0x3f3f3f3f) continue; for (auto x : v[j]) { dp[x][j] = min(dp[x][j], best + abs(i - x)); } } } } for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { if (mat[i][j] == p) return cout << dp[i][j] << endl, 0; } } } ```
#include <bits/stdc++.h> using namespace std; struct IO { char buf[(1 << 20)], *p1, *p2; char pbuf[(1 << 20)], *pp; IO() : p1(buf), p2(buf), pp(pbuf) {} inline char gc() { return getchar(); if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, (1 << 20), stdin); return p1 == p2 ? ' ' : *p1++; } inline bool blank(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; } template <class T> inline void read(T &x) { register double tmp = 1; register bool sign = 0; x = 0; register char ch = gc(); for (; !(ch >= '0' && ch <= '9'); ch = gc()) if (ch == '-') sign = 1; for (; (ch >= '0' && ch <= '9'); ch = gc()) x = x * 10 + (ch - '0'); if (ch == '.') for (ch = gc(); (ch >= '0' && ch <= '9'); ch = gc()) tmp /= 10.0, x += tmp * (ch - '0'); if (sign) x = -x; } inline void read(char *s) { register char ch = gc(); for (; blank(ch); ch = gc()) ; for (; !blank(ch); ch = gc()) *s++ = ch; *s = 0; } inline void read(char &c) { for (c = gc(); blank(c); c = gc()) ; } template <class t> inline void write(t x) { if (x < 0) putchar('-'), write(-x); else { if (x > 9) write(x / 10); putchar('0' + x % 10); } } } io; const int mod = 1e9 + 7; const int mo = 998244353; const int N = 305; const int M = N * N; int n, m, s, f[N][N], a[N][N], ans; struct Node { int x, y; }; vector<Node> xty[M]; inline bool Cmp(Node s, Node t) { return f[s.x][s.y] < f[t.x][t.y]; } inline int Calc(int i, int j, int k, int p) { return abs(i - k) + abs(j - p); } int main() { io.read(n), io.read(m), io.read(s); for (int i = (1); i <= (n); i++) for (int j = (1); j <= (m); j++) { io.read(a[i][j]); xty[a[i][j]].push_back((Node){i, j}); } memset(f, 88, sizeof(f)); for (int i = (0); i <= ((int)xty[1].size() - 1); i++) { int xtyx = xty[1][i].x; int xtyy = xty[1][i].y; f[xtyx][xtyy] = Calc(xtyx, xtyy, 1, 1); } for (int i = (1); i <= (s - 1); i++) { sort(xty[i].begin(), xty[i].end(), Cmp); int MX = min(700, (int)xty[i].size() - 1); for (int j = (0); j <= (MX); j++) { int xtyx = xty[i][j].x; int xtyy = xty[i][j].y; int S = xty[i + 1].size() - 1; for (int k = (0); k <= (S); k++) { int wyyx = xty[i + 1][k].x; int wyyy = xty[i + 1][k].y; f[wyyx][wyyy] = min(f[wyyx][wyyy], f[xtyx][xtyy] + Calc(xtyx, xtyy, wyyx, wyyy)); } } } int Ans = 1e9, S = (int)xty[s].size() - 1; for (int i = (0); i <= (S); i++) { int xtyx = xty[s][i].x; int xtyy = xty[s][i].y; Ans = min(Ans, f[xtyx][xtyy]); } io.write(Ans); return 0; }
### Prompt Create a solution in CPP for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct IO { char buf[(1 << 20)], *p1, *p2; char pbuf[(1 << 20)], *pp; IO() : p1(buf), p2(buf), pp(pbuf) {} inline char gc() { return getchar(); if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, (1 << 20), stdin); return p1 == p2 ? ' ' : *p1++; } inline bool blank(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; } template <class T> inline void read(T &x) { register double tmp = 1; register bool sign = 0; x = 0; register char ch = gc(); for (; !(ch >= '0' && ch <= '9'); ch = gc()) if (ch == '-') sign = 1; for (; (ch >= '0' && ch <= '9'); ch = gc()) x = x * 10 + (ch - '0'); if (ch == '.') for (ch = gc(); (ch >= '0' && ch <= '9'); ch = gc()) tmp /= 10.0, x += tmp * (ch - '0'); if (sign) x = -x; } inline void read(char *s) { register char ch = gc(); for (; blank(ch); ch = gc()) ; for (; !blank(ch); ch = gc()) *s++ = ch; *s = 0; } inline void read(char &c) { for (c = gc(); blank(c); c = gc()) ; } template <class t> inline void write(t x) { if (x < 0) putchar('-'), write(-x); else { if (x > 9) write(x / 10); putchar('0' + x % 10); } } } io; const int mod = 1e9 + 7; const int mo = 998244353; const int N = 305; const int M = N * N; int n, m, s, f[N][N], a[N][N], ans; struct Node { int x, y; }; vector<Node> xty[M]; inline bool Cmp(Node s, Node t) { return f[s.x][s.y] < f[t.x][t.y]; } inline int Calc(int i, int j, int k, int p) { return abs(i - k) + abs(j - p); } int main() { io.read(n), io.read(m), io.read(s); for (int i = (1); i <= (n); i++) for (int j = (1); j <= (m); j++) { io.read(a[i][j]); xty[a[i][j]].push_back((Node){i, j}); } memset(f, 88, sizeof(f)); for (int i = (0); i <= ((int)xty[1].size() - 1); i++) { int xtyx = xty[1][i].x; int xtyy = xty[1][i].y; f[xtyx][xtyy] = Calc(xtyx, xtyy, 1, 1); } for (int i = (1); i <= (s - 1); i++) { sort(xty[i].begin(), xty[i].end(), Cmp); int MX = min(700, (int)xty[i].size() - 1); for (int j = (0); j <= (MX); j++) { int xtyx = xty[i][j].x; int xtyy = xty[i][j].y; int S = xty[i + 1].size() - 1; for (int k = (0); k <= (S); k++) { int wyyx = xty[i + 1][k].x; int wyyy = xty[i + 1][k].y; f[wyyx][wyyy] = min(f[wyyx][wyyy], f[xtyx][xtyy] + Calc(xtyx, xtyy, wyyx, wyyy)); } } } int Ans = 1e9, S = (int)xty[s].size() - 1; for (int i = (0); i <= (S); i++) { int xtyx = xty[s][i].x; int xtyy = xty[s][i].y; Ans = min(Ans, f[xtyx][xtyy]); } io.write(Ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 8; const double eps = 0.1; const int N = 305; const int M = 304 * 305; vector<pair<int, int> > g[M]; int n, m, p; vector<pair<int, int> > v[690]; int ans; pair<int, int> p1, p2; int dp[N][N], dp1[N][N]; int a[N][N]; int val, q, w; void go(int first, int second, int a, int b) { if (a < 1 || a > n || b < 1 || b > m) return; if (dp1[first][second] + 1 < dp1[a][b]) { dp1[a][b] = dp1[first][second] + 1; v[dp1[a][b] - ans].push_back(make_pair(a, b)); } } void out() { cout << endl; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) cout << dp[i][j] << ' '; cout << endl; } } int main() { cin.tie(0); ios_base::sync_with_stdio(0); cin >> n >> m >> p; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) cin >> a[i][j], g[a[i][j]].push_back(make_pair(i, j)); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) dp[i][j] = inf; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (a[i][j] == 1) dp[i][j] = i + j - 2; for (int ite = 1; ite < p; ++ite) { if (g[ite].size() * g[ite + 1].size() < 200123) { for (int i = 0; i < g[ite].size(); ++i) for (int j = 0; j < g[ite + 1].size(); ++j) { p1 = g[ite][i]; p2 = g[ite + 1][j]; dp[p2.first][p2.second] = min(dp[p2.first][p2.second], dp[p1.first][p1.second] + abs(p1.first - p2.first) + abs(p1.second - p2.second)); } } else { ans = inf; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) dp1[i][j] = inf; for (int i = 0; i < g[ite].size(); ++i) { p1 = g[ite][i]; ans = min(ans, dp[p1.first][p1.second]); } for (int i = 0; i < g[ite].size(); ++i) { p1 = g[ite][i]; val = dp[p1.first][p1.second]; if (val - ans > 600) continue; dp1[p1.first][p1.second] = val; v[val - ans].push_back(make_pair(p1.first, p1.second)); } for (int i = 0; i < 605; ++i) { for (int j = 0; j < v[i].size(); ++j) { p1 = v[i][j]; q = p1.first; w = p1.second; go(q, w, q + 1, w); go(q, w, q - 1, w); go(q, w, q, w + 1); go(q, w, q, w - 1); } v[i].clear(); } for (int i = 0; i < g[ite + 1].size(); ++i) { p1 = g[ite + 1][i]; dp[p1.first][p1.second] = dp1[p1.first][p1.second]; } } } ans = inf; for (int i = 0; i < g[p].size(); ++i) { p1 = g[p][i]; ans = min(ans, dp[p1.first][p1.second]); } cout << ans; }
### Prompt Create a solution in Cpp for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 8; const double eps = 0.1; const int N = 305; const int M = 304 * 305; vector<pair<int, int> > g[M]; int n, m, p; vector<pair<int, int> > v[690]; int ans; pair<int, int> p1, p2; int dp[N][N], dp1[N][N]; int a[N][N]; int val, q, w; void go(int first, int second, int a, int b) { if (a < 1 || a > n || b < 1 || b > m) return; if (dp1[first][second] + 1 < dp1[a][b]) { dp1[a][b] = dp1[first][second] + 1; v[dp1[a][b] - ans].push_back(make_pair(a, b)); } } void out() { cout << endl; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) cout << dp[i][j] << ' '; cout << endl; } } int main() { cin.tie(0); ios_base::sync_with_stdio(0); cin >> n >> m >> p; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) cin >> a[i][j], g[a[i][j]].push_back(make_pair(i, j)); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) dp[i][j] = inf; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (a[i][j] == 1) dp[i][j] = i + j - 2; for (int ite = 1; ite < p; ++ite) { if (g[ite].size() * g[ite + 1].size() < 200123) { for (int i = 0; i < g[ite].size(); ++i) for (int j = 0; j < g[ite + 1].size(); ++j) { p1 = g[ite][i]; p2 = g[ite + 1][j]; dp[p2.first][p2.second] = min(dp[p2.first][p2.second], dp[p1.first][p1.second] + abs(p1.first - p2.first) + abs(p1.second - p2.second)); } } else { ans = inf; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) dp1[i][j] = inf; for (int i = 0; i < g[ite].size(); ++i) { p1 = g[ite][i]; ans = min(ans, dp[p1.first][p1.second]); } for (int i = 0; i < g[ite].size(); ++i) { p1 = g[ite][i]; val = dp[p1.first][p1.second]; if (val - ans > 600) continue; dp1[p1.first][p1.second] = val; v[val - ans].push_back(make_pair(p1.first, p1.second)); } for (int i = 0; i < 605; ++i) { for (int j = 0; j < v[i].size(); ++j) { p1 = v[i][j]; q = p1.first; w = p1.second; go(q, w, q + 1, w); go(q, w, q - 1, w); go(q, w, q, w + 1); go(q, w, q, w - 1); } v[i].clear(); } for (int i = 0; i < g[ite + 1].size(); ++i) { p1 = g[ite + 1][i]; dp[p1.first][p1.second] = dp1[p1.first][p1.second]; } } } ans = inf; for (int i = 0; i < g[p].size(); ++i) { p1 = g[p][i]; ans = min(ans, dp[p1.first][p1.second]); } cout << ans; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 300 + 5; const int dx[4] = {1, -1, 0, 0}; const int dy[4] = {0, 0, 1, -1}; int n, m, p; int g[maxn][maxn], d[maxn][maxn]; int dis[maxn][maxn], inq[maxn][maxn]; vector<pair<int, int> > rec[maxn * maxn]; queue<pair<int, int> > que; int main() { memset(d, 63, sizeof(d)); scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &g[i][j]); if (g[i][j] == 1) d[i][j] = i - 1 + j - 1; rec[g[i][j]].push_back(make_pair(i, j)); } int level = sqrt(n * m); int idx = 1; for (int i = 1; i < p; i++) { int sz = rec[i].size(); if (sz <= level) { for (auto v : rec[i + 1]) for (auto u : rec[i]) d[v.first][v.second] = min(d[v.first][v.second], d[u.first][u.second] + abs(v.first - u.first) + abs(v.second - u.second)); } else { idx++; for (auto u : rec[i]) que.push(u); memset(dis, 63, sizeof(dis)); for (auto u : rec[i]) dis[u.first][u.second] = d[u.first][u.second]; while (!que.empty()) { pair<int, int> cur = que.front(); que.pop(); inq[cur.first][cur.second] = 0; for (int k = 0; k < 4; k++) { pair<int, int> nex = cur; nex.first += dx[k]; nex.second += dy[k]; if (nex.first < 1 || nex.first > n) continue; if (nex.second < 1 || nex.second > n) continue; if (dis[nex.first][nex.second] > dis[cur.first][cur.second] + 1) { dis[nex.first][nex.second] = dis[cur.first][cur.second] + 1; if (inq[nex.first][nex.second] < idx) { inq[nex.first][nex.second] = idx; que.push(nex); } } } } for (auto v : rec[i + 1]) d[v.first][v.second] = dis[v.first][v.second]; } } cout << d[rec[p][0].first][rec[p][0].second] << endl; return 0; }
### Prompt Develop a solution in CPP to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 300 + 5; const int dx[4] = {1, -1, 0, 0}; const int dy[4] = {0, 0, 1, -1}; int n, m, p; int g[maxn][maxn], d[maxn][maxn]; int dis[maxn][maxn], inq[maxn][maxn]; vector<pair<int, int> > rec[maxn * maxn]; queue<pair<int, int> > que; int main() { memset(d, 63, sizeof(d)); scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &g[i][j]); if (g[i][j] == 1) d[i][j] = i - 1 + j - 1; rec[g[i][j]].push_back(make_pair(i, j)); } int level = sqrt(n * m); int idx = 1; for (int i = 1; i < p; i++) { int sz = rec[i].size(); if (sz <= level) { for (auto v : rec[i + 1]) for (auto u : rec[i]) d[v.first][v.second] = min(d[v.first][v.second], d[u.first][u.second] + abs(v.first - u.first) + abs(v.second - u.second)); } else { idx++; for (auto u : rec[i]) que.push(u); memset(dis, 63, sizeof(dis)); for (auto u : rec[i]) dis[u.first][u.second] = d[u.first][u.second]; while (!que.empty()) { pair<int, int> cur = que.front(); que.pop(); inq[cur.first][cur.second] = 0; for (int k = 0; k < 4; k++) { pair<int, int> nex = cur; nex.first += dx[k]; nex.second += dy[k]; if (nex.first < 1 || nex.first > n) continue; if (nex.second < 1 || nex.second > n) continue; if (dis[nex.first][nex.second] > dis[cur.first][cur.second] + 1) { dis[nex.first][nex.second] = dis[cur.first][cur.second] + 1; if (inq[nex.first][nex.second] < idx) { inq[nex.first][nex.second] = idx; que.push(nex); } } } } for (auto v : rec[i + 1]) d[v.first][v.second] = dis[v.first][v.second]; } } cout << d[rec[p][0].first][rec[p][0].second] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int Maxn = 301, Mo = 1e9 + 7, INF = INT_MAX; int n, m, p; vector<int> xx[Maxn * Maxn], yy[Maxn * Maxn]; vector<int> w[Maxn]; int d[Maxn][Maxn], a[Maxn][Maxn]; string st; int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { cin >> a[i][j]; xx[a[i][j]].push_back(i); yy[a[i][j]].push_back(j); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) d[i][j] = INF; for (int i = 1; i <= p; i++) { for (int j = 0; j < xx[i].size(); j++) { int x = xx[i][j], y = yy[i][j]; if (i == 1) { d[x][y] = abs(x - 1) + abs(y - 1); } else { for (int k = 1; k <= n; k++) { int pos = lower_bound(w[k].begin(), w[k].end(), y) - w[k].begin(); int len = w[k].size(); if (pos < len && pos >= 0) { int py = w[k][pos]; d[x][y] = min(d[x][y], d[k][py] + abs(x - k) + abs(y - py)); } if (pos + 1 < len) { int py = w[k][pos + 1]; d[x][y] = min(d[x][y], d[k][py] + abs(x - k) + abs(y - py)); } if (pos - 1 >= 0 && pos - 1 < len) { int py = w[k][pos - 1]; d[x][y] = min(d[x][y], d[k][py] + abs(x - k) + abs(y - py)); } } } } for (int j = 1; j <= n; j++) w[j].clear(); for (int j = 0; j < xx[i].size(); j++) { int x = xx[i][j], y = yy[i][j]; w[x].push_back(y); } for (int j = 1; j <= n; j++) sort(w[j].begin(), w[j].end()); } int ans = INF; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == p) ans = min(ans, d[i][j]); cout << ans << endl; }
### Prompt Please create a solution in cpp to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int Maxn = 301, Mo = 1e9 + 7, INF = INT_MAX; int n, m, p; vector<int> xx[Maxn * Maxn], yy[Maxn * Maxn]; vector<int> w[Maxn]; int d[Maxn][Maxn], a[Maxn][Maxn]; string st; int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { cin >> a[i][j]; xx[a[i][j]].push_back(i); yy[a[i][j]].push_back(j); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) d[i][j] = INF; for (int i = 1; i <= p; i++) { for (int j = 0; j < xx[i].size(); j++) { int x = xx[i][j], y = yy[i][j]; if (i == 1) { d[x][y] = abs(x - 1) + abs(y - 1); } else { for (int k = 1; k <= n; k++) { int pos = lower_bound(w[k].begin(), w[k].end(), y) - w[k].begin(); int len = w[k].size(); if (pos < len && pos >= 0) { int py = w[k][pos]; d[x][y] = min(d[x][y], d[k][py] + abs(x - k) + abs(y - py)); } if (pos + 1 < len) { int py = w[k][pos + 1]; d[x][y] = min(d[x][y], d[k][py] + abs(x - k) + abs(y - py)); } if (pos - 1 >= 0 && pos - 1 < len) { int py = w[k][pos - 1]; d[x][y] = min(d[x][y], d[k][py] + abs(x - k) + abs(y - py)); } } } } for (int j = 1; j <= n; j++) w[j].clear(); for (int j = 0; j < xx[i].size(); j++) { int x = xx[i][j], y = yy[i][j]; w[x].push_back(y); } for (int j = 1; j <= n; j++) sort(w[j].begin(), w[j].end()); } int ans = INF; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == p) ans = min(ans, d[i][j]); cout << ans << endl; } ```
#include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:667772160") template <class T1> void deb(T1 e1) { cout << e1 << endl; } template <class T1, class T2> void deb(T1 e1, T2 e2) { cout << e1 << " " << e2 << endl; } template <class T1, class T2, class T3> void deb(T1 e1, T2 e2, T3 e3) { cout << e1 << " " << e2 << " " << e3 << endl; } template <class T1, class T2, class T3, class T4> void deb(T1 e1, T2 e2, T3 e3, T4 e4) { cout << e1 << " " << e2 << " " << e3 << " " << e4 << endl; } template <class T1, class T2, class T3, class T4, class T5> void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5) { cout << e1 << " " << e2 << " " << e3 << " " << e4 << " " << e5 << endl; } template <class T1, class T2, class T3, class T4, class T5, class T6> void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6) { cout << e1 << " " << e2 << " " << e3 << " " << e4 << " " << e5 << " " << e6 << endl; } int dx[] = {0, 0, 1, -1}; int dy[] = {-1, 1, 0, 0}; vector<pair<int, int> > color[90000 + 7]; int level[300 + 7][300 + 7], row, col, cl, dp[300 + 7][300 + 7]; void bfs(int pre) { queue<pair<int, int> > q; int tx, ty; pair<int, int> tp; memset(level, -1, sizeof(level)); for (int i = 0; i < color[pre].size(); i++) { tx = color[pre][i].first; ty = color[pre][i].second; level[tx][ty] = dp[tx][ty]; q.push(make_pair(tx, ty)); } while (!q.empty()) { tp = q.front(); q.pop(); for (int i = 0; i < 4; i++) { tx = tp.first + dx[i]; ty = tp.second + dy[i]; if (tx >= 0 and tx < row and ty >= 0 and ty < col and (level[tx][ty] == -1 or level[tx][ty] > level[tp.first][tp.second] + 1)) { level[tx][ty] = level[tp.first][tp.second] + 1; q.push(make_pair(tx, ty)); } } } } int main() { int a, pre, now; pair<int, int> tp; scanf("%d %d", &row, &col); scanf("%d", &cl); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { scanf("%d", &a); color[a].push_back(make_pair(i, j)); if (a == 1) dp[i][j] = i + j; if (a == cl) tp = make_pair(i, j); } } for (int i = 2; i <= cl; i++) { now = color[i].size(); pre = color[i - 1].size(); if (now * pre < row * col) { int mn = 1800000000; for (int j = 0; j < now; j++) { mn = 1800000000; for (int k = 0; k < pre; k++) { mn = min(mn, dp[color[i - 1][k].first][color[i - 1][k].second] + abs(color[i][j].first - color[i - 1][k].first) + abs(color[i][j].second - color[i - 1][k].second)); } dp[color[i][j].first][color[i][j].second] = mn; } } else { bfs(i - 1); for (int j = 0; j < now; j++) dp[color[i][j].first][color[i][j].second] = level[color[i][j].first][color[i][j].second]; } } deb(dp[tp.first][tp.second]); return 0; }
### Prompt Your task is to create a cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:667772160") template <class T1> void deb(T1 e1) { cout << e1 << endl; } template <class T1, class T2> void deb(T1 e1, T2 e2) { cout << e1 << " " << e2 << endl; } template <class T1, class T2, class T3> void deb(T1 e1, T2 e2, T3 e3) { cout << e1 << " " << e2 << " " << e3 << endl; } template <class T1, class T2, class T3, class T4> void deb(T1 e1, T2 e2, T3 e3, T4 e4) { cout << e1 << " " << e2 << " " << e3 << " " << e4 << endl; } template <class T1, class T2, class T3, class T4, class T5> void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5) { cout << e1 << " " << e2 << " " << e3 << " " << e4 << " " << e5 << endl; } template <class T1, class T2, class T3, class T4, class T5, class T6> void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6) { cout << e1 << " " << e2 << " " << e3 << " " << e4 << " " << e5 << " " << e6 << endl; } int dx[] = {0, 0, 1, -1}; int dy[] = {-1, 1, 0, 0}; vector<pair<int, int> > color[90000 + 7]; int level[300 + 7][300 + 7], row, col, cl, dp[300 + 7][300 + 7]; void bfs(int pre) { queue<pair<int, int> > q; int tx, ty; pair<int, int> tp; memset(level, -1, sizeof(level)); for (int i = 0; i < color[pre].size(); i++) { tx = color[pre][i].first; ty = color[pre][i].second; level[tx][ty] = dp[tx][ty]; q.push(make_pair(tx, ty)); } while (!q.empty()) { tp = q.front(); q.pop(); for (int i = 0; i < 4; i++) { tx = tp.first + dx[i]; ty = tp.second + dy[i]; if (tx >= 0 and tx < row and ty >= 0 and ty < col and (level[tx][ty] == -1 or level[tx][ty] > level[tp.first][tp.second] + 1)) { level[tx][ty] = level[tp.first][tp.second] + 1; q.push(make_pair(tx, ty)); } } } } int main() { int a, pre, now; pair<int, int> tp; scanf("%d %d", &row, &col); scanf("%d", &cl); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { scanf("%d", &a); color[a].push_back(make_pair(i, j)); if (a == 1) dp[i][j] = i + j; if (a == cl) tp = make_pair(i, j); } } for (int i = 2; i <= cl; i++) { now = color[i].size(); pre = color[i - 1].size(); if (now * pre < row * col) { int mn = 1800000000; for (int j = 0; j < now; j++) { mn = 1800000000; for (int k = 0; k < pre; k++) { mn = min(mn, dp[color[i - 1][k].first][color[i - 1][k].second] + abs(color[i][j].first - color[i - 1][k].first) + abs(color[i][j].second - color[i - 1][k].second)); } dp[color[i][j].first][color[i][j].second] = mn; } } else { bfs(i - 1); for (int j = 0; j < now; j++) dp[color[i][j].first][color[i][j].second] = level[color[i][j].first][color[i][j].second]; } } deb(dp[tp.first][tp.second]); return 0; } ```
#include <bits/stdc++.h> #pragma GCC target("sse4,avx") const int64_t inf = 1LL << 60; const int dx[4] = {1, -1, 0, 0}; const int dy[4] = {0, 0, 1, -1}; void run(std::istream& in, std::ostream& out) { int n, m, p; in >> n >> m >> p; std::vector<std::vector<int>> graph(n, std::vector<int>(m, 0)); std::vector<std::vector<std::pair<int, int>>> cells(p); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { in >> graph[i][j]; graph[i][j]--; cells[graph[i][j]].emplace_back(i, j); } } std::vector<std::vector<int64_t>> dist(n, std::vector<int64_t>(m, inf)); if (p == 1) { out << 0 << std::endl; return; } for (std::pair<int, int>& cell : cells[0]) { dist[cell.first][cell.second] = cell.first + cell.second; } std::vector<std::vector<int64_t>> tmp(n, std::vector<int64_t>(m)); for (int ip = 1; ip < p; ip++) { if (uint64_t(cells[ip].size()) * cells[ip - 1].size() < uint64_t(10 * n * m)) { for (std::pair<int, int>& cell : cells[ip]) { int64_t d = inf; for (std::pair<int, int>& cell2 : cells[ip - 1]) { d = std::min(d, dist[cell2.first][cell2.second] + std::abs(cell2.first - cell.first) + std::abs(cell2.second - cell.second)); } dist[cell.first][cell.second] = d; } } else { for (int i = 0; i < n; i++) { std::fill(tmp[i].begin(), tmp[i].end(), inf); } for (std::pair<int, int>& cell : cells[ip - 1]) { tmp[cell.first][cell.second] = dist[cell.first][cell.second]; } std::priority_queue<std::tuple<int64_t, int, int>, std::vector<std::tuple<int64_t, int, int>>, std::greater<std::tuple<int64_t, int, int>>> queue; for (std::pair<int, int>& cell : cells[ip - 1]) { queue.push(std::tuple<int64_t, int, int>{dist[cell.first][cell.second], cell.first, cell.second}); } while (!queue.empty()) { std::tuple<int64_t, int, int> cur = queue.top(); queue.pop(); int64_t d = std::get<0>(cur); int curx = std::get<1>(cur); int cury = std::get<2>(cur); for (int dir = 0; dir < 4; dir++) { int x = curx + dx[dir]; int y = cury + dy[dir]; if (x >= 0 && x < n && y >= 0 && y < m) { if (tmp[x][y] == inf) { queue.push(std::tuple<int64_t, int, int>{d + 1, x, y}); } tmp[x][y] = std::min(tmp[x][y], d + 1); } } } for (std::pair<int, int>& cell : cells[ip]) { dist[cell.first][cell.second] = tmp[cell.first][cell.second]; } } } std::pair<int, int> finalCell = cells[p - 1][0]; out << dist[finalCell.first][finalCell.second] << std::endl; } int main() { std::cin.sync_with_stdio(false); std::cin.tie(nullptr); run(std::cin, std::cout); return 0; }
### Prompt Create a solution in Cpp for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> #pragma GCC target("sse4,avx") const int64_t inf = 1LL << 60; const int dx[4] = {1, -1, 0, 0}; const int dy[4] = {0, 0, 1, -1}; void run(std::istream& in, std::ostream& out) { int n, m, p; in >> n >> m >> p; std::vector<std::vector<int>> graph(n, std::vector<int>(m, 0)); std::vector<std::vector<std::pair<int, int>>> cells(p); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { in >> graph[i][j]; graph[i][j]--; cells[graph[i][j]].emplace_back(i, j); } } std::vector<std::vector<int64_t>> dist(n, std::vector<int64_t>(m, inf)); if (p == 1) { out << 0 << std::endl; return; } for (std::pair<int, int>& cell : cells[0]) { dist[cell.first][cell.second] = cell.first + cell.second; } std::vector<std::vector<int64_t>> tmp(n, std::vector<int64_t>(m)); for (int ip = 1; ip < p; ip++) { if (uint64_t(cells[ip].size()) * cells[ip - 1].size() < uint64_t(10 * n * m)) { for (std::pair<int, int>& cell : cells[ip]) { int64_t d = inf; for (std::pair<int, int>& cell2 : cells[ip - 1]) { d = std::min(d, dist[cell2.first][cell2.second] + std::abs(cell2.first - cell.first) + std::abs(cell2.second - cell.second)); } dist[cell.first][cell.second] = d; } } else { for (int i = 0; i < n; i++) { std::fill(tmp[i].begin(), tmp[i].end(), inf); } for (std::pair<int, int>& cell : cells[ip - 1]) { tmp[cell.first][cell.second] = dist[cell.first][cell.second]; } std::priority_queue<std::tuple<int64_t, int, int>, std::vector<std::tuple<int64_t, int, int>>, std::greater<std::tuple<int64_t, int, int>>> queue; for (std::pair<int, int>& cell : cells[ip - 1]) { queue.push(std::tuple<int64_t, int, int>{dist[cell.first][cell.second], cell.first, cell.second}); } while (!queue.empty()) { std::tuple<int64_t, int, int> cur = queue.top(); queue.pop(); int64_t d = std::get<0>(cur); int curx = std::get<1>(cur); int cury = std::get<2>(cur); for (int dir = 0; dir < 4; dir++) { int x = curx + dx[dir]; int y = cury + dy[dir]; if (x >= 0 && x < n && y >= 0 && y < m) { if (tmp[x][y] == inf) { queue.push(std::tuple<int64_t, int, int>{d + 1, x, y}); } tmp[x][y] = std::min(tmp[x][y], d + 1); } } } for (std::pair<int, int>& cell : cells[ip]) { dist[cell.first][cell.second] = tmp[cell.first][cell.second]; } } } std::pair<int, int> finalCell = cells[p - 1][0]; out << dist[finalCell.first][finalCell.second] << std::endl; } int main() { std::cin.sync_with_stdio(false); std::cin.tie(nullptr); run(std::cin, std::cout); return 0; } ```
#include <bits/stdc++.h> using namespace std; struct data { int x, y, val; data(int X, int Y) { x = X; y = Y; val = 1e9; } }; vector<data> a[int(1e5 + 100)]; int Small, n, m, p; bool cmp(data x, data y) { return x.val < y.val; } bool cmp2(data x, data y) { return x.x < y.x; } int dist(data x, data y) { return abs(x.x - y.x) + abs(x.y - y.y); } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); a[x].push_back(data(i, j)); } Small = 1e9; for (int i = 0; i < a[1].size(); i++) { a[1][i].val = a[1][i].x + a[1][i].y - 2; Small = min(Small, a[1][i].val); } int l = max(0, int(a[1].size()) - n - m); int x = a[1].size() - 1; sort(a[1].begin(), a[1].end(), cmp); while (a[1][x].val - Small > n + m) { l++; x--; } sort(a[1].begin(), a[1].begin() + int(a[1].size()) - l, cmp2); for (int i = 2; i <= p; i++) { Small = 1e9; for (int j = 0; j < a[i].size(); j++) { int tmp = 1e9; for (int k = 0; k < a[i - 1].size() - l; k++) tmp = min(tmp, dist(a[i][j], a[i - 1][k]) + a[i - 1][k].val); Small = min(Small, tmp); a[i][j].val = tmp; } l = max(0, int(a[i].size()) - n - m); sort(a[i].begin(), a[i].end(), cmp); int x = a[i].size() - l - 1; while (a[i][x].val - Small > n + m) { l++; x--; } sort(a[i].begin(), a[i].begin() + int(a[i].size()) - l, cmp2); } int ans = Small; cout << ans; }
### Prompt Please create a solution in cpp to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct data { int x, y, val; data(int X, int Y) { x = X; y = Y; val = 1e9; } }; vector<data> a[int(1e5 + 100)]; int Small, n, m, p; bool cmp(data x, data y) { return x.val < y.val; } bool cmp2(data x, data y) { return x.x < y.x; } int dist(data x, data y) { return abs(x.x - y.x) + abs(x.y - y.y); } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); a[x].push_back(data(i, j)); } Small = 1e9; for (int i = 0; i < a[1].size(); i++) { a[1][i].val = a[1][i].x + a[1][i].y - 2; Small = min(Small, a[1][i].val); } int l = max(0, int(a[1].size()) - n - m); int x = a[1].size() - 1; sort(a[1].begin(), a[1].end(), cmp); while (a[1][x].val - Small > n + m) { l++; x--; } sort(a[1].begin(), a[1].begin() + int(a[1].size()) - l, cmp2); for (int i = 2; i <= p; i++) { Small = 1e9; for (int j = 0; j < a[i].size(); j++) { int tmp = 1e9; for (int k = 0; k < a[i - 1].size() - l; k++) tmp = min(tmp, dist(a[i][j], a[i - 1][k]) + a[i - 1][k].val); Small = min(Small, tmp); a[i][j].val = tmp; } l = max(0, int(a[i].size()) - n - m); sort(a[i].begin(), a[i].end(), cmp); int x = a[i].size() - l - 1; while (a[i][x].val - Small > n + m) { l++; x--; } sort(a[i].begin(), a[i].begin() + int(a[i].size()) - l, cmp2); } int ans = Small; cout << ans; } ```
#include <bits/stdc++.h> using namespace std; inline int in() { int32_t x; scanf("%d", &x); return x; } inline string get() { char ch[1001000]; scanf("%s", ch); return ch; } template <class P, class Q> inline P smin(P &a, Q b) { if (b < a) a = b; return a; } template <class P, class Q> inline P smax(P &a, Q b) { if (a < b) a = b; return a; } const long long maxn = 1e6 + 10; const long long base = 29; const long long MAX_LG = 21; const long long mod = 1e9 + 7; const long long INF = 1e18; vector<pair<long long, long long> > where[maxn]; long long a[350][350]; long long dp[350][350]; long long dx[] = {0, 0, -1, 1}; long long dy[] = {1, -1, 0, 0}; bool mark[350][350]; long long res = 1e18; inline long long dis(long long x, long long y, long long x2, long long y2) { return abs(x - x2) + abs(y - y2); } int32_t main() { long long n = in(), m = in(), p = in(); for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { dp[i][j] = INF; a[i][j] = in(); where[a[i][j]].push_back({i, j}); if (a[i][j] == p) { dp[i][j] = 0; if (p == 1) { res = min(res, i + j); } } } } for (long long i = p - 1; i >= 0; i--) { if (where[i].size() * where[i + 1].size() <= n * m) for (long long pt1 = 0; pt1 < where[i].size(); pt1++) { long long x = where[i][pt1].first, y = where[i][pt1].second; for (long long pt2 = 0; pt2 < where[i + 1].size(); pt2++) { long long x2 = where[i + 1][pt2].first, y2 = where[i + 1][pt2].second; dp[x][y] = min(dp[x][y], dp[x2][y2] + dis(x, y, x2, y2)); } if (i == 1) res = min(res, dp[x][y] + dis(0, 0, x, y)); } else { queue<pair<long long, pair<long long, long long> > > q; for (long long x = 0; x < n; x++) for (long long y = 0; y < m; y++) mark[x][y] = 0; vector<pair<long long, pair<long long, long long> > > vc; for (long long pt = 0; pt < where[i + 1].size(); pt++) { long long x = where[i + 1][pt].first, y = where[i + 1][pt].second; vc.push_back({dp[x][y], {x, y}}); } sort(vc.begin(), vc.end()); q.push(vc[0]); long long cur = 1; while (q.size()) { long long x = q.front().second.first, y = q.front().second.second, d = q.front().first; q.pop(); while (cur < vc.size() && vc[cur].first <= d) q.push(vc[cur++]); for (long long p = 0; p < 4; p++) { long long x2 = x + dx[p], y2 = y + dy[p]; if (x2 >= 0 && x2 < n && y2 >= 0 && y2 < m && !mark[x2][y2]) { if (a[x2][y2] == i) dp[x2][y2] = d + 1; mark[x2][y2] = true; q.push({d + 1, {x2, y2}}); } } } for (long long pt = 0; pt < where[i].size(); pt++) { long long x = where[i][pt].first, y = where[i][pt].second; if (i == 1) res = min(res, dp[x][y] + dis(0, 0, x, y)); } } } cout << res << endl; }
### Prompt Please provide a Cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int in() { int32_t x; scanf("%d", &x); return x; } inline string get() { char ch[1001000]; scanf("%s", ch); return ch; } template <class P, class Q> inline P smin(P &a, Q b) { if (b < a) a = b; return a; } template <class P, class Q> inline P smax(P &a, Q b) { if (a < b) a = b; return a; } const long long maxn = 1e6 + 10; const long long base = 29; const long long MAX_LG = 21; const long long mod = 1e9 + 7; const long long INF = 1e18; vector<pair<long long, long long> > where[maxn]; long long a[350][350]; long long dp[350][350]; long long dx[] = {0, 0, -1, 1}; long long dy[] = {1, -1, 0, 0}; bool mark[350][350]; long long res = 1e18; inline long long dis(long long x, long long y, long long x2, long long y2) { return abs(x - x2) + abs(y - y2); } int32_t main() { long long n = in(), m = in(), p = in(); for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { dp[i][j] = INF; a[i][j] = in(); where[a[i][j]].push_back({i, j}); if (a[i][j] == p) { dp[i][j] = 0; if (p == 1) { res = min(res, i + j); } } } } for (long long i = p - 1; i >= 0; i--) { if (where[i].size() * where[i + 1].size() <= n * m) for (long long pt1 = 0; pt1 < where[i].size(); pt1++) { long long x = where[i][pt1].first, y = where[i][pt1].second; for (long long pt2 = 0; pt2 < where[i + 1].size(); pt2++) { long long x2 = where[i + 1][pt2].first, y2 = where[i + 1][pt2].second; dp[x][y] = min(dp[x][y], dp[x2][y2] + dis(x, y, x2, y2)); } if (i == 1) res = min(res, dp[x][y] + dis(0, 0, x, y)); } else { queue<pair<long long, pair<long long, long long> > > q; for (long long x = 0; x < n; x++) for (long long y = 0; y < m; y++) mark[x][y] = 0; vector<pair<long long, pair<long long, long long> > > vc; for (long long pt = 0; pt < where[i + 1].size(); pt++) { long long x = where[i + 1][pt].first, y = where[i + 1][pt].second; vc.push_back({dp[x][y], {x, y}}); } sort(vc.begin(), vc.end()); q.push(vc[0]); long long cur = 1; while (q.size()) { long long x = q.front().second.first, y = q.front().second.second, d = q.front().first; q.pop(); while (cur < vc.size() && vc[cur].first <= d) q.push(vc[cur++]); for (long long p = 0; p < 4; p++) { long long x2 = x + dx[p], y2 = y + dy[p]; if (x2 >= 0 && x2 < n && y2 >= 0 && y2 < m && !mark[x2][y2]) { if (a[x2][y2] == i) dp[x2][y2] = d + 1; mark[x2][y2] = true; q.push({d + 1, {x2, y2}}); } } } for (long long pt = 0; pt < where[i].size(); pt++) { long long x = where[i][pt].first, y = where[i][pt].second; if (i == 1) res = min(res, dp[x][y] + dis(0, 0, x, y)); } } } cout << res << endl; } ```
#include <bits/stdc++.h> using namespace std; const long long OO = 1e9; const int MAX = 305; vector<pair<int, pair<int, int> > > a[MAX * MAX]; int main() { int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; scanf("%d", &x); a[x].push_back(make_pair(OO, make_pair(i, j))); } a[0].push_back(make_pair(0, make_pair(0, 0))); int t = 0; for (int key = 1; key <= p; key++) { t = !t; sort(((a[key - 1]).begin()), ((a[key - 1]).end())); for (int i = 0; i < a[key].size(); i++) { for (int j = 0; j < min((int)a[key - 1].size(), n + m); j++) { int dis = abs(a[key][i].second.first - a[key - 1][j].second.first) + abs(a[key][i].second.second - a[key - 1][j].second.second); a[key][i].first = min(a[key - 1][j].first + dis, a[key][i].first); } } } cout << a[p][0].first << endl; }
### Prompt Please formulate a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long OO = 1e9; const int MAX = 305; vector<pair<int, pair<int, int> > > a[MAX * MAX]; int main() { int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; scanf("%d", &x); a[x].push_back(make_pair(OO, make_pair(i, j))); } a[0].push_back(make_pair(0, make_pair(0, 0))); int t = 0; for (int key = 1; key <= p; key++) { t = !t; sort(((a[key - 1]).begin()), ((a[key - 1]).end())); for (int i = 0; i < a[key].size(); i++) { for (int j = 0; j < min((int)a[key - 1].size(), n + m); j++) { int dis = abs(a[key][i].second.first - a[key - 1][j].second.first) + abs(a[key][i].second.second - a[key - 1][j].second.second); a[key][i].first = min(a[key - 1][j].first + dis, a[key][i].first); } } } cout << a[p][0].first << endl; } ```
#include <bits/stdc++.h> using namespace std; const int INF = 1 << 30; template <class T> inline T readint(T& a) { a = 0; char c = getchar(); while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') { a = (a << 3) + (a << 1) + c - '0'; c = getchar(); } return a; } struct BIT { int v[310][310]; int h[310][310]; BIT() { memset(h, 0, sizeof h); } void update(const int& a, const int& b, const int& val, const int& d) { for (int i = a; i < 310; i += i & -i) for (int j = b; j < 310; j += j & -j) { if (h[i][j] != d) h[i][j] = d, v[i][j] = INF; v[i][j] = min(v[i][j], val); } } int query(const int& a, const int& b, const int& d) { int ans = INF; for (int i = a; i; i -= i & -i) for (int j = b; j; j -= j & -j) { if (h[i][j] == d) ans = min(v[i][j], ans); } return ans; } } Tree[4]; vector<pair<int, int> > V[90010]; int d[310][310], n, m; void up(const int& i, const int& j, const int& h) { Tree[0].update(i, j, d[i][j] - i - j, h); Tree[1].update(i, m + 1 - j, d[i][j] - i + j, h); Tree[2].update(n + 1 - i, j, d[i][j] + i - j, h); Tree[3].update(n + 1 - i, m + 1 - j, d[i][j] + i + j, h); } int qu(const int& i, const int& j, const int& h) { int& ans = d[i][j]; ans = INF; ans = min(ans, Tree[0].query(i, j, h - 1) + i + j); ans = min(ans, Tree[1].query(i, m + 1 - j, h - 1) + i - j); ans = min(ans, Tree[2].query(n + 1 - i, j, h - 1) - i + j); ans = min(ans, Tree[3].query(n + 1 - i, m + 1 - j, h - 1) - i - j); return ans; } int main() { int p, a; scanf("%d%d%d", &n, &m, &p); for (int i = 1, j; i <= n; ++i) { for (j = 1; j <= m; ++j) { readint(a); V[a].push_back(make_pair(i, j)); if (a <= 1) { d[i][j] = i + j - 2; up(i, j, 1); } } } for (int i = 2; i <= p; ++i) { for (int j = 0; j < V[i].size(); ++j) { qu(V[i][j].first, V[i][j].second, i); } for (int j = 0; j < V[i].size(); ++j) { up(V[i][j].first, V[i][j].second, i); } } printf("%d", d[V[p][0].first][V[p][0].second]); return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = 1 << 30; template <class T> inline T readint(T& a) { a = 0; char c = getchar(); while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') { a = (a << 3) + (a << 1) + c - '0'; c = getchar(); } return a; } struct BIT { int v[310][310]; int h[310][310]; BIT() { memset(h, 0, sizeof h); } void update(const int& a, const int& b, const int& val, const int& d) { for (int i = a; i < 310; i += i & -i) for (int j = b; j < 310; j += j & -j) { if (h[i][j] != d) h[i][j] = d, v[i][j] = INF; v[i][j] = min(v[i][j], val); } } int query(const int& a, const int& b, const int& d) { int ans = INF; for (int i = a; i; i -= i & -i) for (int j = b; j; j -= j & -j) { if (h[i][j] == d) ans = min(v[i][j], ans); } return ans; } } Tree[4]; vector<pair<int, int> > V[90010]; int d[310][310], n, m; void up(const int& i, const int& j, const int& h) { Tree[0].update(i, j, d[i][j] - i - j, h); Tree[1].update(i, m + 1 - j, d[i][j] - i + j, h); Tree[2].update(n + 1 - i, j, d[i][j] + i - j, h); Tree[3].update(n + 1 - i, m + 1 - j, d[i][j] + i + j, h); } int qu(const int& i, const int& j, const int& h) { int& ans = d[i][j]; ans = INF; ans = min(ans, Tree[0].query(i, j, h - 1) + i + j); ans = min(ans, Tree[1].query(i, m + 1 - j, h - 1) + i - j); ans = min(ans, Tree[2].query(n + 1 - i, j, h - 1) - i + j); ans = min(ans, Tree[3].query(n + 1 - i, m + 1 - j, h - 1) - i - j); return ans; } int main() { int p, a; scanf("%d%d%d", &n, &m, &p); for (int i = 1, j; i <= n; ++i) { for (j = 1; j <= m; ++j) { readint(a); V[a].push_back(make_pair(i, j)); if (a <= 1) { d[i][j] = i + j - 2; up(i, j, 1); } } } for (int i = 2; i <= p; ++i) { for (int j = 0; j < V[i].size(); ++j) { qu(V[i][j].first, V[i][j].second, i); } for (int j = 0; j < V[i].size(); ++j) { up(V[i][j].first, V[i][j].second, i); } } printf("%d", d[V[p][0].first][V[p][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXH = 300; const int MAXW = 300; const int MAXVAL = 300 * 300; const int MAXD = MAXH + MAXW - 2; const int DX[] = {-1, 0, +1, 0}, DY[] = {0, +1, 0, -1}; int h, w, nval, dmx; int t[MAXH][MAXW]; int dst[MAXH][MAXW]; int cnt[MAXVAL]; int xhead[MAXVAL], yhead[MAXVAL], xnxt[MAXH][MAXW], ynxt[MAXH][MAXW]; int qxhead[MAXD + 1], qyhead[MAXD + 1], qxnxt[MAXH][MAXW], qynxt[MAXH][MAXW]; int dp[MAXH][MAXW]; void calc(int z) { if (cnt[z] * cnt[z - 1] <= 5 * h * w) { for (int cx = xhead[z], cy = yhead[z], tc; cx != -1 && cy != -1; tc = xnxt[cx][cy], cy = ynxt[cx][cy], cx = tc) { dst[cx][cy] = INT_MAX; for (int px = xhead[z - 1], py = yhead[z - 1], tp; px != -1 && py != -1; tp = xnxt[px][py], py = ynxt[px][py], px = tp) { int cur = dst[px][py] + abs(cx - px) + abs(cy - py); if (cur < dst[cx][cy]) dst[cx][cy] = cur; } } } else { int mn = INT_MAX; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) if (t[x][y] == z - 1 && dst[x][y] < mn) mn = dst[x][y]; for (int d = (0); d <= (dmx); ++d) qxhead[d] = qyhead[d] = -1; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) dp[x][y] = INT_MAX; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) if (t[x][y] == z - 1) { int d = dst[x][y] - mn; assert(d <= dmx); qxnxt[x][y] = qxhead[d], qynxt[x][y] = qyhead[d], qxhead[d] = x, qyhead[d] = y; dp[x][y] = dst[x][y]; } for (int d = (0); d <= (dmx); ++d) for (int x = qxhead[d], y = qyhead[d], tmp; x != -1 && y != -1; tmp = qxnxt[x][y], y = qynxt[x][y], x = tmp) for (int k = (0); k < (4); ++k) { int nx = x + DX[k], ny = y + DY[k]; if (nx < 0 || nx >= h || ny < 0 || ny >= w || dp[nx][ny] <= dp[x][y] + 1) continue; assert(d + 1 <= dmx); qxnxt[nx][ny] = qxhead[d + 1], qynxt[nx][ny] = qyhead[d + 1], qxhead[d + 1] = nx, qyhead[d + 1] = ny; dp[nx][ny] = dp[x][y] + 1; } for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) if (t[x][y] == z) dst[x][y] = dp[x][y]; } } void run() { scanf("%d%d%d", &h, &w, &nval); dmx = h + w - 2; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) scanf("%d", &t[x][y]), --t[x][y]; for (int i = (0); i < (nval); ++i) cnt[i] = 0, xhead[i] = -1, yhead[i] = -1; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) xnxt[x][y] = xhead[t[x][y]], ynxt[x][y] = yhead[t[x][y]], xhead[t[x][y]] = x, yhead[t[x][y]] = y, ++cnt[t[x][y]]; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) dst[x][y] = t[x][y] == 0 ? x + y : -2; for (int i = (1); i < (nval); ++i) calc(i); for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) if (t[x][y] == nval - 1) { printf("%d\n", dst[x][y]); return; } printf("-1\n"); } int main() { run(); return 0; }
### Prompt Please formulate a Cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXH = 300; const int MAXW = 300; const int MAXVAL = 300 * 300; const int MAXD = MAXH + MAXW - 2; const int DX[] = {-1, 0, +1, 0}, DY[] = {0, +1, 0, -1}; int h, w, nval, dmx; int t[MAXH][MAXW]; int dst[MAXH][MAXW]; int cnt[MAXVAL]; int xhead[MAXVAL], yhead[MAXVAL], xnxt[MAXH][MAXW], ynxt[MAXH][MAXW]; int qxhead[MAXD + 1], qyhead[MAXD + 1], qxnxt[MAXH][MAXW], qynxt[MAXH][MAXW]; int dp[MAXH][MAXW]; void calc(int z) { if (cnt[z] * cnt[z - 1] <= 5 * h * w) { for (int cx = xhead[z], cy = yhead[z], tc; cx != -1 && cy != -1; tc = xnxt[cx][cy], cy = ynxt[cx][cy], cx = tc) { dst[cx][cy] = INT_MAX; for (int px = xhead[z - 1], py = yhead[z - 1], tp; px != -1 && py != -1; tp = xnxt[px][py], py = ynxt[px][py], px = tp) { int cur = dst[px][py] + abs(cx - px) + abs(cy - py); if (cur < dst[cx][cy]) dst[cx][cy] = cur; } } } else { int mn = INT_MAX; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) if (t[x][y] == z - 1 && dst[x][y] < mn) mn = dst[x][y]; for (int d = (0); d <= (dmx); ++d) qxhead[d] = qyhead[d] = -1; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) dp[x][y] = INT_MAX; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) if (t[x][y] == z - 1) { int d = dst[x][y] - mn; assert(d <= dmx); qxnxt[x][y] = qxhead[d], qynxt[x][y] = qyhead[d], qxhead[d] = x, qyhead[d] = y; dp[x][y] = dst[x][y]; } for (int d = (0); d <= (dmx); ++d) for (int x = qxhead[d], y = qyhead[d], tmp; x != -1 && y != -1; tmp = qxnxt[x][y], y = qynxt[x][y], x = tmp) for (int k = (0); k < (4); ++k) { int nx = x + DX[k], ny = y + DY[k]; if (nx < 0 || nx >= h || ny < 0 || ny >= w || dp[nx][ny] <= dp[x][y] + 1) continue; assert(d + 1 <= dmx); qxnxt[nx][ny] = qxhead[d + 1], qynxt[nx][ny] = qyhead[d + 1], qxhead[d + 1] = nx, qyhead[d + 1] = ny; dp[nx][ny] = dp[x][y] + 1; } for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) if (t[x][y] == z) dst[x][y] = dp[x][y]; } } void run() { scanf("%d%d%d", &h, &w, &nval); dmx = h + w - 2; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) scanf("%d", &t[x][y]), --t[x][y]; for (int i = (0); i < (nval); ++i) cnt[i] = 0, xhead[i] = -1, yhead[i] = -1; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) xnxt[x][y] = xhead[t[x][y]], ynxt[x][y] = yhead[t[x][y]], xhead[t[x][y]] = x, yhead[t[x][y]] = y, ++cnt[t[x][y]]; for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) dst[x][y] = t[x][y] == 0 ? x + y : -2; for (int i = (1); i < (nval); ++i) calc(i); for (int x = (0); x < (h); ++x) for (int y = (0); y < (w); ++y) if (t[x][y] == nval - 1) { printf("%d\n", dst[x][y]); return; } printf("-1\n"); } int main() { run(); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAXN = 305; int n, m, p; int arr[MAXN][MAXN]; vector<pair<int, int> > pos[MAXN * MAXN]; int ma[MAXN * MAXN]; int cnt = 0; int dist[MAXN][MAXN][MAXN]; int xx[4] = {-1, 1, 0, 0}; int yy[4] = {0, 0, -1, 1}; int dp[MAXN][MAXN]; int di[MAXN][MAXN]; int ur[MAXN][MAXN]; int ul[MAXN][MAXN]; int dr[MAXN][MAXN]; int dl[MAXN][MAXN]; int main() { ios_base::sync_with_stdio(0); cin >> n >> m >> p; for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) cin >> arr[g][y]; for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) pos[arr[g][y]].push_back(pair<int, int>(g, y)); for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) dp[g][y] = 1e9; for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) { if (arr[g][y] == p) dp[g][y] = 0; } for (int g = p - 1; g >= 1; g--) { if (pos[g + 1].size() >= 300) { for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) { di[g][y] = ur[g][y] = ul[g][y] = dr[g][y] = dl[g][y] = 1e9; } for (pair<int, int> t : pos[g + 1]) { di[t.first][t.second] = dp[t.first][t.second]; } for (int y = 1; y <= n; y++) { for (int z = 1; z <= m; z++) { ul[y][z] = di[y][z]; if (y != 1) ul[y][z] = min(ul[y][z], 1 + ul[y - 1][z]); if (z != 1) ul[y][z] = min(ul[y][z], 1 + ul[y][z - 1]); } } for (int y = n; y >= 1; y--) { for (int z = m; z >= 1; z--) { dr[y][z] = di[y][z]; if (y != n) dr[y][z] = min(dr[y][z], 1 + dr[y + 1][z]); if (z != m) dr[y][z] = min(dr[y][z], 1 + dr[y][z + 1]); } } for (int y = n; y >= 1; y--) { for (int z = 1; z <= m; z++) { dl[y][z] = di[y][z]; if (y != n) dl[y][z] = min(dl[y][z], 1 + dl[y + 1][z]); if (z != 1) dl[y][z] = min(dl[y][z], 1 + dl[y][z - 1]); } } for (int y = 1; y <= n; y++) { for (int z = m; z >= 1; z--) { ur[y][z] = di[y][z]; if (y != 1) ur[y][z] = min(ur[y][z], 1 + ur[y - 1][z]); if (z != m) ur[y][z] = min(ur[y][z], 1 + ur[y][z + 1]); } } for (pair<int, int> t : pos[g]) { int a = t.first, b = t.second; dp[a][b] = min({ul[a][b], ur[a][b], dl[a][b], dr[a][b]}); } } else { for (pair<int, int> t : pos[g]) { for (pair<int, int> y : pos[g + 1]) { dp[t.first][t.second] = min(dp[t.first][t.second], abs(t.first - y.first) + abs(t.second - y.second) + dp[y.first][y.second]); } } } } int answer = 2e9; for (int g = 1; g <= n; g++) { for (int y = 1; y <= m; y++) { if (arr[g][y] == 1) { answer = min(answer, g + y - 2 + dp[g][y]); } } } cout << answer << '\n'; return 0; }
### Prompt In CPP, your task is to solve the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 305; int n, m, p; int arr[MAXN][MAXN]; vector<pair<int, int> > pos[MAXN * MAXN]; int ma[MAXN * MAXN]; int cnt = 0; int dist[MAXN][MAXN][MAXN]; int xx[4] = {-1, 1, 0, 0}; int yy[4] = {0, 0, -1, 1}; int dp[MAXN][MAXN]; int di[MAXN][MAXN]; int ur[MAXN][MAXN]; int ul[MAXN][MAXN]; int dr[MAXN][MAXN]; int dl[MAXN][MAXN]; int main() { ios_base::sync_with_stdio(0); cin >> n >> m >> p; for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) cin >> arr[g][y]; for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) pos[arr[g][y]].push_back(pair<int, int>(g, y)); for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) dp[g][y] = 1e9; for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) { if (arr[g][y] == p) dp[g][y] = 0; } for (int g = p - 1; g >= 1; g--) { if (pos[g + 1].size() >= 300) { for (int g = 1; g <= n; g++) for (int y = 1; y <= m; y++) { di[g][y] = ur[g][y] = ul[g][y] = dr[g][y] = dl[g][y] = 1e9; } for (pair<int, int> t : pos[g + 1]) { di[t.first][t.second] = dp[t.first][t.second]; } for (int y = 1; y <= n; y++) { for (int z = 1; z <= m; z++) { ul[y][z] = di[y][z]; if (y != 1) ul[y][z] = min(ul[y][z], 1 + ul[y - 1][z]); if (z != 1) ul[y][z] = min(ul[y][z], 1 + ul[y][z - 1]); } } for (int y = n; y >= 1; y--) { for (int z = m; z >= 1; z--) { dr[y][z] = di[y][z]; if (y != n) dr[y][z] = min(dr[y][z], 1 + dr[y + 1][z]); if (z != m) dr[y][z] = min(dr[y][z], 1 + dr[y][z + 1]); } } for (int y = n; y >= 1; y--) { for (int z = 1; z <= m; z++) { dl[y][z] = di[y][z]; if (y != n) dl[y][z] = min(dl[y][z], 1 + dl[y + 1][z]); if (z != 1) dl[y][z] = min(dl[y][z], 1 + dl[y][z - 1]); } } for (int y = 1; y <= n; y++) { for (int z = m; z >= 1; z--) { ur[y][z] = di[y][z]; if (y != 1) ur[y][z] = min(ur[y][z], 1 + ur[y - 1][z]); if (z != m) ur[y][z] = min(ur[y][z], 1 + ur[y][z + 1]); } } for (pair<int, int> t : pos[g]) { int a = t.first, b = t.second; dp[a][b] = min({ul[a][b], ur[a][b], dl[a][b], dr[a][b]}); } } else { for (pair<int, int> t : pos[g]) { for (pair<int, int> y : pos[g + 1]) { dp[t.first][t.second] = min(dp[t.first][t.second], abs(t.first - y.first) + abs(t.second - y.second) + dp[y.first][y.second]); } } } } int answer = 2e9; for (int g = 1; g <= n; g++) { for (int y = 1; y <= m; y++) { if (arr[g][y] == 1) { answer = min(answer, g + y - 2 + dp[g][y]); } } } cout << answer << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int z = 300; struct cool { int x, y, d; }; vector<cool> a[z * z + 1]; int n, m, p; bool comp(cool a, cool b) { return (a.d < b.d); } int main() { cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; cool c; cin >> x; c.x = i; c.y = j; if (x == 1) c.d = i + j; else c.d = 1e9; a[x].push_back(c); } for (int i = 2; i <= p; i++) { sort(a[i - 1].begin(), a[i - 1].end(), comp); for (int j = 0; j < a[i].size(); j++) for (int l = 0; l < min((int)a[i - 1].size(), n + m); l++) a[i][j].d = min(a[i][j].d, a[i - 1][l].d + abs(a[i - 1][l].x - a[i][j].x) + abs(a[i - 1][l].y - a[i][j].y)); } cout << a[p][0].d; return 0; }
### Prompt Please create a solution in cpp to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int z = 300; struct cool { int x, y, d; }; vector<cool> a[z * z + 1]; int n, m, p; bool comp(cool a, cool b) { return (a.d < b.d); } int main() { cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; cool c; cin >> x; c.x = i; c.y = j; if (x == 1) c.d = i + j; else c.d = 1e9; a[x].push_back(c); } for (int i = 2; i <= p; i++) { sort(a[i - 1].begin(), a[i - 1].end(), comp); for (int j = 0; j < a[i].size(); j++) for (int l = 0; l < min((int)a[i - 1].size(), n + m); l++) a[i][j].d = min(a[i][j].d, a[i - 1][l].d + abs(a[i - 1][l].x - a[i][j].x) + abs(a[i - 1][l].y - a[i][j].y)); } cout << a[p][0].d; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 303; const int P = N * N; const int OO = P * N * 2; int val[N][N]; int new_val[N][N]; int last[N][N]; vector<pair<int, int>> pos[P]; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { int x; cin >> x; pos[x].emplace_back(i, j); val[i][j] = i + j; } } int ans = OO; for (int kind = 1; kind <= p; ++kind) { for (auto& ps : pos[kind]) { int value = OO; for (int i = 0; i < m; ++i) { if (last[ps.first][i] < kind - 1) continue; value = min(value, val[ps.first][i] + abs(ps.second - i)); } new_val[ps.first][ps.second] = value; if (kind == p) { ans = min(ans, value); } } for (auto& ps : pos[kind]) { int value = new_val[ps.first][ps.second]; for (int i = 0; i < n; ++i) { if (last[i][ps.second] == kind) { val[i][ps.second] = min(val[i][ps.second], value + abs(i - ps.first)); } else { val[i][ps.second] = value + abs(i - ps.first); } last[i][ps.second] = kind; } } } cout << ans; }
### Prompt Please create a solution in cpp to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 303; const int P = N * N; const int OO = P * N * 2; int val[N][N]; int new_val[N][N]; int last[N][N]; vector<pair<int, int>> pos[P]; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { int x; cin >> x; pos[x].emplace_back(i, j); val[i][j] = i + j; } } int ans = OO; for (int kind = 1; kind <= p; ++kind) { for (auto& ps : pos[kind]) { int value = OO; for (int i = 0; i < m; ++i) { if (last[ps.first][i] < kind - 1) continue; value = min(value, val[ps.first][i] + abs(ps.second - i)); } new_val[ps.first][ps.second] = value; if (kind == p) { ans = min(ans, value); } } for (auto& ps : pos[kind]) { int value = new_val[ps.first][ps.second]; for (int i = 0; i < n; ++i) { if (last[i][ps.second] == kind) { val[i][ps.second] = min(val[i][ps.second], value + abs(i - ps.first)); } else { val[i][ps.second] = value + abs(i - ps.first); } last[i][ps.second] = kind; } } } cout << ans; } ```
#include <bits/stdc++.h> using namespace std; const int N = 305; int dp[N][N], d[N][N], a[N][N], n, m, p; class Grid { public: int row, col; Grid(int row, int col) { this->row = row; this->col = col; } }; class Data { public: int val, row, col; Data(int val, int row, int col) { this->val = val; this->row = row; this->col = col; } bool operator<(const Data &other) const { return val < other.val; } }; bool isInside(int x, int y) { return (x >= 1 && x <= n && y >= 1 && y <= m); } int dist(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } vector<Grid> g[N * N]; int main() { scanf("%d %d %d", &n, &m, &p); memset(dp, 0x3f, sizeof(dp)); int dx, dy; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) dp[i][j] = i + j - 2; if (a[i][j] == p) { dx = i; dy = j; } g[a[i][j]].push_back(Grid(i, j)); } } for (int i = 2; i <= p; i++) { int cur = g[i].size(); int last = g[i - 1].size(); if (cur * last <= n * m) { for (int j = 0; j < cur; j++) { for (int k = 0; k < last; k++) { dp[g[i][j].row][g[i][j].col] = min(dp[g[i][j].row][g[i][j].col], dp[g[i - 1][k].row][g[i - 1][k].col] + dist(g[i][j].row, g[i][j].col, g[i - 1][k].row, g[i - 1][k].col)); } } } else { memset(d, -1, sizeof(d)); queue<Data> q; vector<Data> v; for (int j = 0; j < last; j++) { int x = g[i - 1][j].row; int y = g[i - 1][j].col; v.push_back(Data(dp[x][y], x, y)); } sort(v.begin(), v.end()); q.push(v[0]); int pt = 1; d[v[0].row][v[0].col] = v[0].val; while (!q.empty()) { Data u = q.front(); q.pop(); int x = u.row; int y = u.col; int val = u.val; while (pt < v.size() && v[pt].val <= val) q.push(v[pt++]); for (int d_x = -1; d_x <= 1; d_x++) { for (int d_y = -1; d_y <= 1; d_y++) { if (d_x * d_y != 0 || d_x + d_y == 0) continue; if (!isInside(x + d_x, y + d_y)) continue; if (d[x + d_x][y + d_y] != -1) continue; d[x + d_x][y + d_y] = val + 1; q.push(Data(val + 1, x + d_x, y + d_y)); } } } for (int j = 0; j < cur; j++) { dp[g[i][j].row][g[i][j].col] = d[g[i][j].row][g[i][j].col]; } } } printf("%d", dp[dx][dy]); return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 305; int dp[N][N], d[N][N], a[N][N], n, m, p; class Grid { public: int row, col; Grid(int row, int col) { this->row = row; this->col = col; } }; class Data { public: int val, row, col; Data(int val, int row, int col) { this->val = val; this->row = row; this->col = col; } bool operator<(const Data &other) const { return val < other.val; } }; bool isInside(int x, int y) { return (x >= 1 && x <= n && y >= 1 && y <= m); } int dist(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } vector<Grid> g[N * N]; int main() { scanf("%d %d %d", &n, &m, &p); memset(dp, 0x3f, sizeof(dp)); int dx, dy; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) dp[i][j] = i + j - 2; if (a[i][j] == p) { dx = i; dy = j; } g[a[i][j]].push_back(Grid(i, j)); } } for (int i = 2; i <= p; i++) { int cur = g[i].size(); int last = g[i - 1].size(); if (cur * last <= n * m) { for (int j = 0; j < cur; j++) { for (int k = 0; k < last; k++) { dp[g[i][j].row][g[i][j].col] = min(dp[g[i][j].row][g[i][j].col], dp[g[i - 1][k].row][g[i - 1][k].col] + dist(g[i][j].row, g[i][j].col, g[i - 1][k].row, g[i - 1][k].col)); } } } else { memset(d, -1, sizeof(d)); queue<Data> q; vector<Data> v; for (int j = 0; j < last; j++) { int x = g[i - 1][j].row; int y = g[i - 1][j].col; v.push_back(Data(dp[x][y], x, y)); } sort(v.begin(), v.end()); q.push(v[0]); int pt = 1; d[v[0].row][v[0].col] = v[0].val; while (!q.empty()) { Data u = q.front(); q.pop(); int x = u.row; int y = u.col; int val = u.val; while (pt < v.size() && v[pt].val <= val) q.push(v[pt++]); for (int d_x = -1; d_x <= 1; d_x++) { for (int d_y = -1; d_y <= 1; d_y++) { if (d_x * d_y != 0 || d_x + d_y == 0) continue; if (!isInside(x + d_x, y + d_y)) continue; if (d[x + d_x][y + d_y] != -1) continue; d[x + d_x][y + d_y] = val + 1; q.push(Data(val + 1, x + d_x, y + d_y)); } } } for (int j = 0; j < cur; j++) { dp[g[i][j].row][g[i][j].col] = d[g[i][j].row][g[i][j].col]; } } } printf("%d", dp[dx][dy]); return 0; } ```
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > in[300 * 300 + 1]; int dp[300][300]; void smin(int &a, int b) { a = min(a, b); } int main() { for (int i = 0; i < 300; i++) fill(dp[i], dp[i] + 300, 1e9); int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int x; scanf("%d", &x); in[x].push_back(make_pair(i, j)); } } in[0].push_back(make_pair(0, 0)); dp[0][0] = 0; for (int i = 1; i <= p; i++) { for (auto cur : in[i]) { if (in[i - 1].size() < n) { for (int j = 0; j < in[i - 1].size(); j++) smin(dp[cur.first][cur.second], dp[in[i - 1][j].first][in[i - 1][j].second] + abs(in[i - 1][j].first - cur.first) + abs(in[i - 1][j].second - cur.second)); continue; } for (int ro = 0; ro < n; ro++) { vector<pair<int, int> >::iterator up = upper_bound( in[i - 1].begin(), in[i - 1].end(), make_pair(ro, cur.second)); if (up->first == ro && up != in[i - 1].end()) smin(dp[cur.first][cur.second], dp[up->first][up->second] + abs(up->first - cur.first) + abs(up->second - cur.second)); if (up != in[i - 1].begin()) { up--; if (up->first == ro) smin(dp[cur.first][cur.second], dp[up->first][up->second] + abs(up->first - cur.first) + abs(up->second - cur.second)); } } } if (i == 1 && in[1][0] != make_pair(0, 0)) dp[0][0] = 1e9; } printf("%d", dp[in[p][0].first][in[p][0].second]); }
### Prompt Create a solution in cpp for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<pair<int, int> > in[300 * 300 + 1]; int dp[300][300]; void smin(int &a, int b) { a = min(a, b); } int main() { for (int i = 0; i < 300; i++) fill(dp[i], dp[i] + 300, 1e9); int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int x; scanf("%d", &x); in[x].push_back(make_pair(i, j)); } } in[0].push_back(make_pair(0, 0)); dp[0][0] = 0; for (int i = 1; i <= p; i++) { for (auto cur : in[i]) { if (in[i - 1].size() < n) { for (int j = 0; j < in[i - 1].size(); j++) smin(dp[cur.first][cur.second], dp[in[i - 1][j].first][in[i - 1][j].second] + abs(in[i - 1][j].first - cur.first) + abs(in[i - 1][j].second - cur.second)); continue; } for (int ro = 0; ro < n; ro++) { vector<pair<int, int> >::iterator up = upper_bound( in[i - 1].begin(), in[i - 1].end(), make_pair(ro, cur.second)); if (up->first == ro && up != in[i - 1].end()) smin(dp[cur.first][cur.second], dp[up->first][up->second] + abs(up->first - cur.first) + abs(up->second - cur.second)); if (up != in[i - 1].begin()) { up--; if (up->first == ro) smin(dp[cur.first][cur.second], dp[up->first][up->second] + abs(up->first - cur.first) + abs(up->second - cur.second)); } } } if (i == 1 && in[1][0] != make_pair(0, 0)) dp[0][0] = 1e9; } printf("%d", dp[in[p][0].first][in[p][0].second]); } ```
#include <bits/stdc++.h> using namespace std; const int N = 600005; const long long mod = (long long)1e9 + 7; int a[305][305], n, m; int dist[305][305], val[100000], tmpdist[305][305]; int di[4] = {0, 1, 0, -1}; int dj[4] = {1, 0, -1, 0}; vector<vector<pair<int, int> > > l; int diff(pair<int, int> u, pair<int, int> v) { return abs(u.first - v.first) + abs(u.second - v.second); } bool bound(int i, int j) { if (i >= 0 && i < n && j >= 0 && j < m) return 1; return 0; } void bfs(int color) { priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; memset(tmpdist, -1, sizeof tmpdist); for (int i = 0, t = l[color - 1].size(); i < t; i++) { pair<int, int> u = l[color - 1][i]; pq.push(make_pair(dist[u.first][u.second], u)); tmpdist[u.first][u.second] = dist[u.first][u.second]; } while (!pq.empty()) { pair<int, pair<int, int> > p = pq.top(); pq.pop(); int d = p.first; pair<int, int> u = p.second; if (d > tmpdist[u.first][u.second]) continue; for (int k = 0, t = 4; k < t; k++) { int ui = u.first + di[k], uj = u.second + dj[k]; if (bound(ui, uj) && (tmpdist[ui][uj] == -1 || tmpdist[ui][uj] > d + 1)) { tmpdist[ui][uj] = d + 1; pq.push(make_pair(d + 1, pair<int, int>(ui, uj))); } } } } int main() { ios_base::sync_with_stdio(false); int p; cin >> n >> m >> p; l.resize(p + 1); for (int i = 0, t = n; i < t; i++) { for (int j = 0, t = m; j < t; j++) { cin >> a[i][j]; int v = i * m + j; val[v] = a[i][j]; l[a[i][j]].push_back(pair<int, int>(i, j)); if (a[i][j] == 1) dist[i][j] = i + j; else dist[i][j] = 1e9; } } for (int i = 2, t = p + 1; i < t; i++) { if (l[i].size() * l[i - 1].size() < 10 * n * m) { for (int j = 0, t = l[i].size(); j < t; j++) { int mn = 1e9; pair<int, int> u = l[i][j]; for (int k = 0, t = l[i - 1].size(); k < t; k++) { pair<int, int> v = l[i - 1][k]; mn = min(mn, dist[v.first][v.second] + diff(u, v)); } dist[u.first][u.second] = mn; } } else { bfs(i); for (int j = 0, t = l[i].size(); j < t; j++) { pair<int, int> u = l[i][j]; dist[u.first][u.second] = tmpdist[u.first][u.second]; } } } cout << dist[l[p][0].first][l[p][0].second] << '\n'; }
### Prompt Create a solution in Cpp for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 600005; const long long mod = (long long)1e9 + 7; int a[305][305], n, m; int dist[305][305], val[100000], tmpdist[305][305]; int di[4] = {0, 1, 0, -1}; int dj[4] = {1, 0, -1, 0}; vector<vector<pair<int, int> > > l; int diff(pair<int, int> u, pair<int, int> v) { return abs(u.first - v.first) + abs(u.second - v.second); } bool bound(int i, int j) { if (i >= 0 && i < n && j >= 0 && j < m) return 1; return 0; } void bfs(int color) { priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; memset(tmpdist, -1, sizeof tmpdist); for (int i = 0, t = l[color - 1].size(); i < t; i++) { pair<int, int> u = l[color - 1][i]; pq.push(make_pair(dist[u.first][u.second], u)); tmpdist[u.first][u.second] = dist[u.first][u.second]; } while (!pq.empty()) { pair<int, pair<int, int> > p = pq.top(); pq.pop(); int d = p.first; pair<int, int> u = p.second; if (d > tmpdist[u.first][u.second]) continue; for (int k = 0, t = 4; k < t; k++) { int ui = u.first + di[k], uj = u.second + dj[k]; if (bound(ui, uj) && (tmpdist[ui][uj] == -1 || tmpdist[ui][uj] > d + 1)) { tmpdist[ui][uj] = d + 1; pq.push(make_pair(d + 1, pair<int, int>(ui, uj))); } } } } int main() { ios_base::sync_with_stdio(false); int p; cin >> n >> m >> p; l.resize(p + 1); for (int i = 0, t = n; i < t; i++) { for (int j = 0, t = m; j < t; j++) { cin >> a[i][j]; int v = i * m + j; val[v] = a[i][j]; l[a[i][j]].push_back(pair<int, int>(i, j)); if (a[i][j] == 1) dist[i][j] = i + j; else dist[i][j] = 1e9; } } for (int i = 2, t = p + 1; i < t; i++) { if (l[i].size() * l[i - 1].size() < 10 * n * m) { for (int j = 0, t = l[i].size(); j < t; j++) { int mn = 1e9; pair<int, int> u = l[i][j]; for (int k = 0, t = l[i - 1].size(); k < t; k++) { pair<int, int> v = l[i - 1][k]; mn = min(mn, dist[v.first][v.second] + diff(u, v)); } dist[u.first][u.second] = mn; } } else { bfs(i); for (int j = 0, t = l[i].size(); j < t; j++) { pair<int, int> u = l[i][j]; dist[u.first][u.second] = tmpdist[u.first][u.second]; } } } cout << dist[l[p][0].first][l[p][0].second] << '\n'; } ```
#include <bits/stdc++.h> using namespace std; const long long maxn = 1e6 + 6, inf = 1e18, mod = 1e9 + 7; long long n, m, p, dis[305][305], a[305][305], tmp[305][305]; vector<pair<int, int> > vec[305 * 305], V; bool mark[305][305]; int main() { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> n >> m >> p; if (p == 1) return cout << 0 << endl, 0; for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { cin >> a[i][j]; vec[a[i][j]].push_back({i, j}); if (a[i][j] == 1) { dis[i][j] = i + j; mark[i][j] = 1; V.push_back({i, j}); } else dis[i][j] = inf; } } long long x = 1; while (x < p) { for (auto i : vec[x]) tmp[i.first][i.second] = dis[i.first][i.second]; for (auto i : V) { dis[i.first][i.second] = inf; mark[i.first][i.second] = 0; } V.clear(); for (auto i : vec[x]) { dis[i.first][i.second] = tmp[i.first][i.second]; for (long long j = 0; j < m; j++) { dis[i.first][j] = min(dis[i.first][j], dis[i.first][i.second] + abs(i.second - j)); if (!mark[i.first][j]) { V.push_back({i.first, j}); mark[i.first][j] = 1; } } for (long long j = 0; j < n; j++) { dis[j][i.second] = min(dis[j][i.second], dis[i.first][i.second] + abs(j - i.first)); if (!mark[j][i.second]) { V.push_back({j, i.second}); mark[j][i.second] = 1; } } } for (auto i : vec[x + 1]) { for (long long j = 0; j < m; j++) dis[i.first][i.second] = min(dis[i.first][i.second], dis[i.first][j] + abs(j - i.second)); for (long long j = 0; j < n; j++) dis[i.first][i.second] = min(dis[i.first][i.second], dis[j][i.second] + abs(i.first - j)); if (!mark[i.first][i.second]) { V.push_back({i.first, i.second}); mark[i.first][i.second] = 1; } } x++; } cout << dis[vec[p][0].first][vec[p][0].second] << endl; }
### Prompt Generate a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long maxn = 1e6 + 6, inf = 1e18, mod = 1e9 + 7; long long n, m, p, dis[305][305], a[305][305], tmp[305][305]; vector<pair<int, int> > vec[305 * 305], V; bool mark[305][305]; int main() { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> n >> m >> p; if (p == 1) return cout << 0 << endl, 0; for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { cin >> a[i][j]; vec[a[i][j]].push_back({i, j}); if (a[i][j] == 1) { dis[i][j] = i + j; mark[i][j] = 1; V.push_back({i, j}); } else dis[i][j] = inf; } } long long x = 1; while (x < p) { for (auto i : vec[x]) tmp[i.first][i.second] = dis[i.first][i.second]; for (auto i : V) { dis[i.first][i.second] = inf; mark[i.first][i.second] = 0; } V.clear(); for (auto i : vec[x]) { dis[i.first][i.second] = tmp[i.first][i.second]; for (long long j = 0; j < m; j++) { dis[i.first][j] = min(dis[i.first][j], dis[i.first][i.second] + abs(i.second - j)); if (!mark[i.first][j]) { V.push_back({i.first, j}); mark[i.first][j] = 1; } } for (long long j = 0; j < n; j++) { dis[j][i.second] = min(dis[j][i.second], dis[i.first][i.second] + abs(j - i.first)); if (!mark[j][i.second]) { V.push_back({j, i.second}); mark[j][i.second] = 1; } } } for (auto i : vec[x + 1]) { for (long long j = 0; j < m; j++) dis[i.first][i.second] = min(dis[i.first][i.second], dis[i.first][j] + abs(j - i.second)); for (long long j = 0; j < n; j++) dis[i.first][i.second] = min(dis[i.first][i.second], dis[j][i.second] + abs(i.first - j)); if (!mark[i.first][i.second]) { V.push_back({i.first, i.second}); mark[i.first][i.second] = 1; } } x++; } cout << dis[vec[p][0].first][vec[p][0].second] << endl; } ```
#include <bits/stdc++.h> using namespace std; const int N = 310; const int dx[4] = {0, 0, -1, 1}, dy[4] = {1, -1, 0, 0}; vector<pair<int, int> > g[N * N]; int n, m, p, gx, gy; int f[N][N], d[N][N]; queue<pair<int, pair<int, int> > > q; vector<pair<int, pair<int, int> > > gg; bool valid(int x, int y) { return (x <= n && y <= m && x > 0 && y > 0 && (d[x][y] == -1)); } int main() { memset(f, 0x3f, sizeof(f)); cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int x; cin >> x; g[x].push_back(pair<int, int>(i, j)); if (x == 1) { f[i][j] = i + j - 2; } if (x == p) { gx = i, gy = j; } } } for (int i = 2; i <= p; i++) { int curs = g[i].size(), ls = g[i - 1].size(); if (curs * ls <= n * m) { for (int k = 0; k < curs; k++) { int curx = g[i][k].first, cury = g[i][k].second; for (int j = 0; j < ls; j++) { int lx = g[i - 1][j].first, ly = g[i - 1][j].second; f[curx][cury] = min(f[curx][cury], f[lx][ly] + abs(lx - curx) + abs(ly - cury)); } } } else { for (int k = 1; k <= n; k++) { for (int j = 1; j <= m; j++) d[k][j] = -1; } while (!q.empty()) q.pop(); gg.clear(); for (int k = 0; k < ls; k++) { int x = g[i - 1][k].first, y = g[i - 1][k].second; gg.push_back(pair<int, pair<int, int> >(f[x][y], pair<int, int>(x, y))); } sort(gg.begin(), gg.end()); q.push(gg[0]); d[gg[0].second.first][gg[0].second.second] = gg[0].first; int j = 1; while (!q.empty()) { pair<int, pair<int, int> > cur = q.front(); q.pop(); int x = cur.second.first, y = cur.second.second, dis = cur.first; while (j < ls && gg[j].first <= dis) { q.push(gg[j++]); } for (int k = 0; k < 4; k++) { int nx = x + dx[k], ny = y + dy[k]; if (valid(nx, ny)) { d[nx][ny] = dis + 1; q.push( pair<int, pair<int, int> >(d[nx][ny], pair<int, int>(nx, ny))); } } } for (int k = 0; k < curs; k++) { int curx = g[i][k].first, cury = g[i][k].second; f[curx][cury] = d[curx][cury]; } } } cout << f[gx][gy] << endl; return 0; }
### Prompt Create a solution in CPP for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 310; const int dx[4] = {0, 0, -1, 1}, dy[4] = {1, -1, 0, 0}; vector<pair<int, int> > g[N * N]; int n, m, p, gx, gy; int f[N][N], d[N][N]; queue<pair<int, pair<int, int> > > q; vector<pair<int, pair<int, int> > > gg; bool valid(int x, int y) { return (x <= n && y <= m && x > 0 && y > 0 && (d[x][y] == -1)); } int main() { memset(f, 0x3f, sizeof(f)); cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int x; cin >> x; g[x].push_back(pair<int, int>(i, j)); if (x == 1) { f[i][j] = i + j - 2; } if (x == p) { gx = i, gy = j; } } } for (int i = 2; i <= p; i++) { int curs = g[i].size(), ls = g[i - 1].size(); if (curs * ls <= n * m) { for (int k = 0; k < curs; k++) { int curx = g[i][k].first, cury = g[i][k].second; for (int j = 0; j < ls; j++) { int lx = g[i - 1][j].first, ly = g[i - 1][j].second; f[curx][cury] = min(f[curx][cury], f[lx][ly] + abs(lx - curx) + abs(ly - cury)); } } } else { for (int k = 1; k <= n; k++) { for (int j = 1; j <= m; j++) d[k][j] = -1; } while (!q.empty()) q.pop(); gg.clear(); for (int k = 0; k < ls; k++) { int x = g[i - 1][k].first, y = g[i - 1][k].second; gg.push_back(pair<int, pair<int, int> >(f[x][y], pair<int, int>(x, y))); } sort(gg.begin(), gg.end()); q.push(gg[0]); d[gg[0].second.first][gg[0].second.second] = gg[0].first; int j = 1; while (!q.empty()) { pair<int, pair<int, int> > cur = q.front(); q.pop(); int x = cur.second.first, y = cur.second.second, dis = cur.first; while (j < ls && gg[j].first <= dis) { q.push(gg[j++]); } for (int k = 0; k < 4; k++) { int nx = x + dx[k], ny = y + dy[k]; if (valid(nx, ny)) { d[nx][ny] = dis + 1; q.push( pair<int, pair<int, int> >(d[nx][ny], pair<int, int>(nx, ny))); } } } for (int k = 0; k < curs; k++) { int curx = g[i][k].first, cury = g[i][k].second; f[curx][cury] = d[curx][cury]; } } } cout << f[gx][gy] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 10; const int N = 305; const int M = 1e9 + 7; int n, m, k, p; int d[N][N]; vector<vector<pair<int, int>>> vec; vector<pair<int, int>> dist[3][N]; inline int getDIST(int x, int y, int xx, int yy) { return abs(x - xx) + abs(y - yy); } int main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> d[i][j]; vec.resize(p + 1); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) vec[d[i][j]].push_back(make_pair(i, j)); for (int i = 0; i < vec[1].size(); i++) { int x = vec[1][i].first; int y = vec[1][i].second; int d = getDIST(1, 1, x, y); dist[1][y].push_back({d, x}); } int t = 1; int nt = 2; for (int i = 2; i <= p; i++) { for (int j = 1; j <= m; j++) { sort(dist[t][j].begin(), dist[t][j].end()); dist[nt][j].clear(); } for (int h = 0; h < vec[i].size(); h++) { int x = vec[i][h].first; int y = vec[i][h].second; int w = INF; for (int j = 1; j <= m; j++) { int k = 0; int dy = abs(j - y); while (k < dist[t][j].size() && w > dist[t][j][k].first + dy) { w = min(w, dist[t][j][k].first + abs(dist[t][j][k].second - x) + dy); k++; } } dist[nt][y].push_back({w, x}); } swap(t, nt); } int ans = INF; for (int i = 1; i <= m; i++) for (int j = 0; j < dist[t][i].size(); j++) ans = min(ans, dist[t][i][j].first); cout << ans; return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 10; const int N = 305; const int M = 1e9 + 7; int n, m, k, p; int d[N][N]; vector<vector<pair<int, int>>> vec; vector<pair<int, int>> dist[3][N]; inline int getDIST(int x, int y, int xx, int yy) { return abs(x - xx) + abs(y - yy); } int main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> d[i][j]; vec.resize(p + 1); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) vec[d[i][j]].push_back(make_pair(i, j)); for (int i = 0; i < vec[1].size(); i++) { int x = vec[1][i].first; int y = vec[1][i].second; int d = getDIST(1, 1, x, y); dist[1][y].push_back({d, x}); } int t = 1; int nt = 2; for (int i = 2; i <= p; i++) { for (int j = 1; j <= m; j++) { sort(dist[t][j].begin(), dist[t][j].end()); dist[nt][j].clear(); } for (int h = 0; h < vec[i].size(); h++) { int x = vec[i][h].first; int y = vec[i][h].second; int w = INF; for (int j = 1; j <= m; j++) { int k = 0; int dy = abs(j - y); while (k < dist[t][j].size() && w > dist[t][j][k].first + dy) { w = min(w, dist[t][j][k].first + abs(dist[t][j][k].second - x) + dy); k++; } } dist[nt][y].push_back({w, x}); } swap(t, nt); } int ans = INF; for (int i = 1; i <= m; i++) for (int j = 0; j < dist[t][i].size(); j++) ans = min(ans, dist[t][i][j].first); cout << ans; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAX = 300 + 5; int n, m, p; int grid[MAX][MAX]; int dp[MAX][MAX]; vector<pair<int, int> > pos[MAX * MAX]; vector<int> col[MAX]; int main() { scanf("%d %d %d", &n, &m, &p); for (int i = int(0); i < int(n); i++) { for (int j = int(0); j < int(m); j++) { scanf("%d", &grid[i][j]); if (grid[i][j] == 1) { dp[i][j] = i + j; } else { dp[i][j] = 1 << 30; } pos[grid[i][j]].emplace_back(i, j); } } bool visited[MAX]; for (int i = int(1); i < int(p); i++) { memset(visited, false, sizeof visited); for (int c = int(0); c < int(m); c++) { col[c].clear(); } for (auto &each : pos[i + 1]) { col[each.second].push_back(each.first); } for (auto &each : pos[i]) { visited[each.first] = true; } for (int r = int(0); r < int(n); r++) { if (visited[r]) { int best = 1 << 30; for (int c = int(0); c < int(m); c++) { best++; if (grid[r][c] == i) { best = min(best, dp[r][c]); } for (auto &each : col[c]) { dp[each][c] = min(dp[each][c], best + abs(each - r)); } } best = 1 << 30; for (int c = int(m - 1); c >= int(0); c--) { best++; if (grid[r][c] == i) { best = min(best, dp[r][c]); } for (auto &each : col[c]) { dp[each][c] = min(dp[each][c], best + abs(each - r)); } } } } } printf("%d\n", dp[pos[p][0].first][pos[p][0].second]); return 0; }
### Prompt In CPP, your task is to solve the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAX = 300 + 5; int n, m, p; int grid[MAX][MAX]; int dp[MAX][MAX]; vector<pair<int, int> > pos[MAX * MAX]; vector<int> col[MAX]; int main() { scanf("%d %d %d", &n, &m, &p); for (int i = int(0); i < int(n); i++) { for (int j = int(0); j < int(m); j++) { scanf("%d", &grid[i][j]); if (grid[i][j] == 1) { dp[i][j] = i + j; } else { dp[i][j] = 1 << 30; } pos[grid[i][j]].emplace_back(i, j); } } bool visited[MAX]; for (int i = int(1); i < int(p); i++) { memset(visited, false, sizeof visited); for (int c = int(0); c < int(m); c++) { col[c].clear(); } for (auto &each : pos[i + 1]) { col[each.second].push_back(each.first); } for (auto &each : pos[i]) { visited[each.first] = true; } for (int r = int(0); r < int(n); r++) { if (visited[r]) { int best = 1 << 30; for (int c = int(0); c < int(m); c++) { best++; if (grid[r][c] == i) { best = min(best, dp[r][c]); } for (auto &each : col[c]) { dp[each][c] = min(dp[each][c], best + abs(each - r)); } } best = 1 << 30; for (int c = int(m - 1); c >= int(0); c--) { best++; if (grid[r][c] == i) { best = min(best, dp[r][c]); } for (auto &each : col[c]) { dp[each][c] = min(dp[each][c], best + abs(each - r)); } } } } } printf("%d\n", dp[pos[p][0].first][pos[p][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; struct Point { int x, y, c; Point() {} Point(int x, int y, int c) : x(x), y(y), c(c) {} }; const int INF = 1e9; int n, m, p; vector<vector<Point> > pt; vector<vector<int> > dp; vector<vector<int> > a; inline int dist(const Point& p1, const Point& p2) { return abs(p1.x - p2.x) + abs(p1.y - p2.y); } int main() { cin >> n >> m >> p; pt = vector<vector<Point> >(p); a = vector<vector<int> >(n, vector<int>(m)); for (int i = 0; i < (int)(n); i++) { for (int j = 0; j < (int)(m); j++) { cin >> a[i][j]; a[i][j]--; pt[a[i][j]].push_back(Point(i, j, a[i][j])); } } dp = vector<vector<int> >(n, vector<int>(m, INF)); for (int i = 0; i < (int)(n); i++) for (int j = 0; j < (int)(m); j++) if (a[i][j] == 0) dp[i][j] = i + j; for (int i = 0; i < (int)(p - 1); i++) { vector<Point> v = pt[i]; for (auto p : pt[i + 1]) v.push_back(p); sort(v.begin(), v.end(), [](const Point& p1, const Point& p2) { if (p1.y != p2.y) return (p1.y < p2.y); return p1.c < p2.c; }); vector<int> d(n, INF); int l = 0; while (l < v.size()) { int r = l; while (r < v.size() && v[l].y == v[r].y) r++; int add = v[l].y; for (int j = l; j < r; j++) { if (v[j].c == i) { d[v[j].x] = dp[v[j].x][v[j].y] - add; } else { for (int x = 0; x < (int)(n); x++) { dp[v[j].x][v[j].y] = min(dp[v[j].x][v[j].y], d[x] + add + abs(x - v[j].x)); } } } l = r; } sort(v.begin(), v.end(), [](const Point& p1, const Point& p2) { if (p1.y != p2.y) return (p1.y > p2.y); return p1.c < p2.c; }); d = vector<int>(n, INF); l = 0; while (l < v.size()) { int r = l; while (r < v.size() && v[l].y == v[r].y) r++; int add = m - 1 - v[l].y; for (int j = l; j < r; j++) { if (v[j].c == i) { d[v[j].x] = dp[v[j].x][v[j].y] - add; } else { for (int x = 0; x < (int)(n); x++) { dp[v[j].x][v[j].y] = min(dp[v[j].x][v[j].y], d[x] + add + abs(x - v[j].x)); } } } l = r; } } cout << dp[pt[p - 1][0].x][pt[p - 1][0].y] << endl; return 0; }
### Prompt Please create a solution in cpp to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct Point { int x, y, c; Point() {} Point(int x, int y, int c) : x(x), y(y), c(c) {} }; const int INF = 1e9; int n, m, p; vector<vector<Point> > pt; vector<vector<int> > dp; vector<vector<int> > a; inline int dist(const Point& p1, const Point& p2) { return abs(p1.x - p2.x) + abs(p1.y - p2.y); } int main() { cin >> n >> m >> p; pt = vector<vector<Point> >(p); a = vector<vector<int> >(n, vector<int>(m)); for (int i = 0; i < (int)(n); i++) { for (int j = 0; j < (int)(m); j++) { cin >> a[i][j]; a[i][j]--; pt[a[i][j]].push_back(Point(i, j, a[i][j])); } } dp = vector<vector<int> >(n, vector<int>(m, INF)); for (int i = 0; i < (int)(n); i++) for (int j = 0; j < (int)(m); j++) if (a[i][j] == 0) dp[i][j] = i + j; for (int i = 0; i < (int)(p - 1); i++) { vector<Point> v = pt[i]; for (auto p : pt[i + 1]) v.push_back(p); sort(v.begin(), v.end(), [](const Point& p1, const Point& p2) { if (p1.y != p2.y) return (p1.y < p2.y); return p1.c < p2.c; }); vector<int> d(n, INF); int l = 0; while (l < v.size()) { int r = l; while (r < v.size() && v[l].y == v[r].y) r++; int add = v[l].y; for (int j = l; j < r; j++) { if (v[j].c == i) { d[v[j].x] = dp[v[j].x][v[j].y] - add; } else { for (int x = 0; x < (int)(n); x++) { dp[v[j].x][v[j].y] = min(dp[v[j].x][v[j].y], d[x] + add + abs(x - v[j].x)); } } } l = r; } sort(v.begin(), v.end(), [](const Point& p1, const Point& p2) { if (p1.y != p2.y) return (p1.y > p2.y); return p1.c < p2.c; }); d = vector<int>(n, INF); l = 0; while (l < v.size()) { int r = l; while (r < v.size() && v[l].y == v[r].y) r++; int add = m - 1 - v[l].y; for (int j = l; j < r; j++) { if (v[j].c == i) { d[v[j].x] = dp[v[j].x][v[j].y] - add; } else { for (int x = 0; x < (int)(n); x++) { dp[v[j].x][v[j].y] = min(dp[v[j].x][v[j].y], d[x] + add + abs(x - v[j].x)); } } } l = r; } } cout << dp[pt[p - 1][0].x][pt[p - 1][0].y] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; const int SIZE = 1e6 + 5; const long long INF = 1LL << 58; const double eps = 1e-13; int v[309][309]; vector<pair<int, int> > c[90009]; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; int dist[309][309]; int main() { int n, m, p; scanf("%d%d%d", &n, &m, &p); if (p == 1) { printf("%d", n + m - 2); return 0; } for (int i = 0; i < (n); ++i) { for (int j = 0; j < (m); ++j) { scanf("%d", &(v[i][j])); v[i][j]--; c[v[i][j]].push_back(make_pair(i, j)); } } for (pair<int, int> cp : c[0]) { dist[cp.first][cp.second] = cp.first + cp.second; } for (int i = (1); i < (p); ++i) { if (((int)(c[i]).size()) * ((int)(c[i - 1]).size()) < 500000) { for (pair<int, int> cp : c[i]) { dist[cp.first][cp.second] = 1 << 30; for (pair<int, int> pp : c[i - 1]) { dist[cp.first][cp.second] = min(dist[cp.first][cp.second], dist[pp.first][pp.second] + abs(pp.first - cp.first) + abs(pp.second - cp.second)); } } } else { priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; int cc = 0; for (int j = 0; j < (n); ++j) { for (int k = 0; k < (m); ++k) { if (v[j][k] != i - 1) dist[j][k] = -1; } } for (pair<int, int> cp : c[i - 1]) { pq.push(make_pair(dist[cp.first][cp.second], cp)); } while (((int)(pq).size())) { auto cur = pq.top(); pq.pop(); int d = cur.first, y = cur.second.first, x = cur.second.second; if (d > dist[y][x]) continue; if (v[y][x] == i) cc++; if (cc == ((int)(c[i]).size())) break; for (int dir = 0; dir < (4); ++dir) { int ny = y + dy[dir], nx = x + dx[dir], nd = d + 1; if (ny < 0 || nx < 0 || ny >= n || nx >= m) continue; if (dist[ny][nx] != -1 && dist[ny][nx] <= nd) continue; dist[ny][nx] = nd; pq.push(make_pair(nd, make_pair(ny, nx))); } } } } printf("%d", dist[c[p - 1][0].first][c[p - 1][0].second]); }
### Prompt In CPP, your task is to solve the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; const int SIZE = 1e6 + 5; const long long INF = 1LL << 58; const double eps = 1e-13; int v[309][309]; vector<pair<int, int> > c[90009]; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; int dist[309][309]; int main() { int n, m, p; scanf("%d%d%d", &n, &m, &p); if (p == 1) { printf("%d", n + m - 2); return 0; } for (int i = 0; i < (n); ++i) { for (int j = 0; j < (m); ++j) { scanf("%d", &(v[i][j])); v[i][j]--; c[v[i][j]].push_back(make_pair(i, j)); } } for (pair<int, int> cp : c[0]) { dist[cp.first][cp.second] = cp.first + cp.second; } for (int i = (1); i < (p); ++i) { if (((int)(c[i]).size()) * ((int)(c[i - 1]).size()) < 500000) { for (pair<int, int> cp : c[i]) { dist[cp.first][cp.second] = 1 << 30; for (pair<int, int> pp : c[i - 1]) { dist[cp.first][cp.second] = min(dist[cp.first][cp.second], dist[pp.first][pp.second] + abs(pp.first - cp.first) + abs(pp.second - cp.second)); } } } else { priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; int cc = 0; for (int j = 0; j < (n); ++j) { for (int k = 0; k < (m); ++k) { if (v[j][k] != i - 1) dist[j][k] = -1; } } for (pair<int, int> cp : c[i - 1]) { pq.push(make_pair(dist[cp.first][cp.second], cp)); } while (((int)(pq).size())) { auto cur = pq.top(); pq.pop(); int d = cur.first, y = cur.second.first, x = cur.second.second; if (d > dist[y][x]) continue; if (v[y][x] == i) cc++; if (cc == ((int)(c[i]).size())) break; for (int dir = 0; dir < (4); ++dir) { int ny = y + dy[dir], nx = x + dx[dir], nd = d + 1; if (ny < 0 || nx < 0 || ny >= n || nx >= m) continue; if (dist[ny][nx] != -1 && dist[ny][nx] <= nd) continue; dist[ny][nx] = nd; pq.push(make_pair(nd, make_pair(ny, nx))); } } } } printf("%d", dist[c[p - 1][0].first][c[p - 1][0].second]); } ```
#include <bits/stdc++.h> using namespace std; const int N = 100100; int n, m, x; long long dis[400][400]; long long d[400][400]; int dx[] = {0, 0, -1, 1}; int dy[] = {-1, 1, 0, 0}; vector<pair<int, int> > v[N]; bool in(int i, int j) { return 1 <= i && i <= n && 1 <= j && j <= m; } int main() { for (int i = 0; i < 400; i++) for (int j = 0; j < 400; j++) dis[i][j] = 1ll << 50; cin >> n >> m >> x; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int d; cin >> d; v[d].push_back({i, j}); if (d == 1) dis[i][j] = i - 1 + j - 1; } for (int i = 1; i < x; i++) { vector<pair<int, int> > a = v[i]; vector<pair<int, int> > b = v[i + 1]; if (a.size() * b.size() <= n * m) { for (int j = 0; j < a.size(); j++) for (int k = 0; k < b.size(); k++) dis[b[k].first][b[k].second] = min(dis[b[k].first][b[k].second], dis[a[j].first][a[j].second] + abs(a[j].first - b[k].first) + abs(b[k].second - a[j].second)); } else { memset(d, 100, sizeof d); queue<pair<int, int> > Q; for (auto x : a) d[x.first][x.second] = dis[x.first][x.second]; for (auto x : a) Q.push(x); while (!Q.empty()) { int x = Q.front().first; int y = Q.front().second; Q.pop(); for (int k = 0; k < 4; k++) { int nx = dx[k] + x; int ny = dy[k] + y; if (!in(nx, ny)) continue; if (d[nx][ny] <= 1 + d[x][y]) continue; d[nx][ny] = 1 + d[x][y]; Q.push({nx, ny}); } } for (auto x : b) dis[x.first][x.second] = d[x.first][x.second]; } } long long ans = dis[v[x][0].first][v[x][0].second]; cout << ans << endl; return 0; }
### Prompt Develop a solution in cpp to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 100100; int n, m, x; long long dis[400][400]; long long d[400][400]; int dx[] = {0, 0, -1, 1}; int dy[] = {-1, 1, 0, 0}; vector<pair<int, int> > v[N]; bool in(int i, int j) { return 1 <= i && i <= n && 1 <= j && j <= m; } int main() { for (int i = 0; i < 400; i++) for (int j = 0; j < 400; j++) dis[i][j] = 1ll << 50; cin >> n >> m >> x; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int d; cin >> d; v[d].push_back({i, j}); if (d == 1) dis[i][j] = i - 1 + j - 1; } for (int i = 1; i < x; i++) { vector<pair<int, int> > a = v[i]; vector<pair<int, int> > b = v[i + 1]; if (a.size() * b.size() <= n * m) { for (int j = 0; j < a.size(); j++) for (int k = 0; k < b.size(); k++) dis[b[k].first][b[k].second] = min(dis[b[k].first][b[k].second], dis[a[j].first][a[j].second] + abs(a[j].first - b[k].first) + abs(b[k].second - a[j].second)); } else { memset(d, 100, sizeof d); queue<pair<int, int> > Q; for (auto x : a) d[x.first][x.second] = dis[x.first][x.second]; for (auto x : a) Q.push(x); while (!Q.empty()) { int x = Q.front().first; int y = Q.front().second; Q.pop(); for (int k = 0; k < 4; k++) { int nx = dx[k] + x; int ny = dy[k] + y; if (!in(nx, ny)) continue; if (d[nx][ny] <= 1 + d[x][y]) continue; d[nx][ny] = 1 + d[x][y]; Q.push({nx, ny}); } } for (auto x : b) dis[x.first][x.second] = d[x.first][x.second]; } } long long ans = dis[v[x][0].first][v[x][0].second]; cout << ans << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > V[310 * 310]; int dx[4] = {0, -1, 0, 1}; int dy[4] = {1, 0, -1, 0}; int a[310][310]; int dp[310][310]; int dis[310][310]; int vis[310][310]; int main() { int n, m, p; cin >> n >> m >> p; memset(dp, (127), sizeof(dp)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); V[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) dp[i][j] = i - 1 + j - 1; } queue<pair<int, int> > Q; int level = sqrt(n * m); for (int i = 1; i < p; i++) { if (V[i].size() <= level) { for (int j = 0; j < V[i + 1].size(); j++) { for (int k = 0; k < V[i].size(); k++) { dp[V[i + 1][j].first][V[i + 1][j].second] = min(dp[V[i + 1][j].first][V[i + 1][j].second], dp[V[i][k].first][V[i][k].second] + abs(V[i + 1][j].first - V[i][k].first) + abs(V[i + 1][j].second - V[i][k].second)); } } } else { memset(dis, (127), sizeof(dis)); for (int j = 0; j < V[i].size(); j++) { dis[V[i][j].first][V[i][j].second] = dp[V[i][j].first][V[i][j].second]; Q.push(V[i][j]); } while (!Q.empty()) { pair<int, int> now = Q.front(); Q.pop(); pair<int, int> next; for (int k = 0; k < 4; k++) { next.first = now.first + dx[k]; next.second = now.second + dy[k]; if (next.first > n || next.first < 1) continue; if (next.second > m || next.second < 1) continue; if (dis[next.first][next.second] > dis[now.first][now.second] + 1) { dis[next.first][next.second] = dis[now.first][now.second] + 1; if (a[next.first][next.second] != i + 1) { Q.push(next); } } } } for (int j = 0; j < V[i + 1].size(); j++) { dp[V[i + 1][j].first][V[i + 1][j].second] = dis[V[i + 1][j].first][V[i + 1][j].second]; } } } printf("%d\n", dp[V[p][0].first][V[p][0].second]); return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<pair<int, int> > V[310 * 310]; int dx[4] = {0, -1, 0, 1}; int dy[4] = {1, 0, -1, 0}; int a[310][310]; int dp[310][310]; int dis[310][310]; int vis[310][310]; int main() { int n, m, p; cin >> n >> m >> p; memset(dp, (127), sizeof(dp)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); V[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) dp[i][j] = i - 1 + j - 1; } queue<pair<int, int> > Q; int level = sqrt(n * m); for (int i = 1; i < p; i++) { if (V[i].size() <= level) { for (int j = 0; j < V[i + 1].size(); j++) { for (int k = 0; k < V[i].size(); k++) { dp[V[i + 1][j].first][V[i + 1][j].second] = min(dp[V[i + 1][j].first][V[i + 1][j].second], dp[V[i][k].first][V[i][k].second] + abs(V[i + 1][j].first - V[i][k].first) + abs(V[i + 1][j].second - V[i][k].second)); } } } else { memset(dis, (127), sizeof(dis)); for (int j = 0; j < V[i].size(); j++) { dis[V[i][j].first][V[i][j].second] = dp[V[i][j].first][V[i][j].second]; Q.push(V[i][j]); } while (!Q.empty()) { pair<int, int> now = Q.front(); Q.pop(); pair<int, int> next; for (int k = 0; k < 4; k++) { next.first = now.first + dx[k]; next.second = now.second + dy[k]; if (next.first > n || next.first < 1) continue; if (next.second > m || next.second < 1) continue; if (dis[next.first][next.second] > dis[now.first][now.second] + 1) { dis[next.first][next.second] = dis[now.first][now.second] + 1; if (a[next.first][next.second] != i + 1) { Q.push(next); } } } } for (int j = 0; j < V[i + 1].size(); j++) { dp[V[i + 1][j].first][V[i + 1][j].second] = dis[V[i + 1][j].first][V[i + 1][j].second]; } } } printf("%d\n", dp[V[p][0].first][V[p][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; int a[302][302], tmp[302][302], dis[302][302]; int dx[] = {0, 0, 1, -1}; int dy[] = {-1, 1, 0, 0}; vector<pair<int, int> > v[(int)9e4 + 3]; int main() { int t, i, j, n, q, k, l, r, c, fnl; scanf("%d %d %d", &r, &c, &fnl); for (i = 1; i <= r; i++) { for (j = 1; j <= c; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) { dis[i][j] = i + j - 2; } else { dis[i][j] = (int)1e9 + 7; } v[a[i][j]].push_back(make_pair(i, j)); } } for (k = 2; k <= fnl; k++) { int sz1 = v[k - 1].size(); int sz2 = v[k].size(); if (sz1 * sz2 >= r * c) { queue<int> q; for (i = 1; i <= r; i++) { for (j = 1; j <= c; j++) { tmp[i][j] = -1; if (a[i][j] == k - 1) { tmp[i][j] = dis[i][j]; q.push(i); q.push(j); } } } while (!q.empty()) { int x = q.front(); q.pop(); int y = q.front(); q.pop(); for (i = 0; i <= 3; i++) { int x1 = x + dx[i]; int y1 = y + dy[i]; if ((x1 >= 1 && x1 <= r) && (y1 >= 1 && y1 <= c) && (tmp[x1][y1] < 0 || tmp[x1][y1] > tmp[x][y] + 1)) { tmp[x1][y1] = tmp[x][y] + 1; if (a[x1][y1] == k) { dis[x1][y1] = min(dis[x1][y1], tmp[x1][y1]); } q.push(x1); q.push(y1); } } } } else { for (i = 0; i <= sz1 - 1; i++) { for (j = 0; j <= sz2 - 1; j++) { dis[v[k][j].first][v[k][j].second] = min(dis[v[k][j].first][v[k][j].second], dis[v[k - 1][i].first][v[k - 1][i].second] + abs(v[k][j].first - v[k - 1][i].first) + abs(v[k][j].second - v[k - 1][i].second)); } } } } printf("%d\n", dis[v[fnl][0].first][v[fnl][0].second]); return 0; }
### Prompt Construct a cpp code solution to the problem outlined: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int a[302][302], tmp[302][302], dis[302][302]; int dx[] = {0, 0, 1, -1}; int dy[] = {-1, 1, 0, 0}; vector<pair<int, int> > v[(int)9e4 + 3]; int main() { int t, i, j, n, q, k, l, r, c, fnl; scanf("%d %d %d", &r, &c, &fnl); for (i = 1; i <= r; i++) { for (j = 1; j <= c; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) { dis[i][j] = i + j - 2; } else { dis[i][j] = (int)1e9 + 7; } v[a[i][j]].push_back(make_pair(i, j)); } } for (k = 2; k <= fnl; k++) { int sz1 = v[k - 1].size(); int sz2 = v[k].size(); if (sz1 * sz2 >= r * c) { queue<int> q; for (i = 1; i <= r; i++) { for (j = 1; j <= c; j++) { tmp[i][j] = -1; if (a[i][j] == k - 1) { tmp[i][j] = dis[i][j]; q.push(i); q.push(j); } } } while (!q.empty()) { int x = q.front(); q.pop(); int y = q.front(); q.pop(); for (i = 0; i <= 3; i++) { int x1 = x + dx[i]; int y1 = y + dy[i]; if ((x1 >= 1 && x1 <= r) && (y1 >= 1 && y1 <= c) && (tmp[x1][y1] < 0 || tmp[x1][y1] > tmp[x][y] + 1)) { tmp[x1][y1] = tmp[x][y] + 1; if (a[x1][y1] == k) { dis[x1][y1] = min(dis[x1][y1], tmp[x1][y1]); } q.push(x1); q.push(y1); } } } } else { for (i = 0; i <= sz1 - 1; i++) { for (j = 0; j <= sz2 - 1; j++) { dis[v[k][j].first][v[k][j].second] = min(dis[v[k][j].first][v[k][j].second], dis[v[k - 1][i].first][v[k - 1][i].second] + abs(v[k][j].first - v[k - 1][i].first) + abs(v[k][j].second - v[k - 1][i].second)); } } } } printf("%d\n", dis[v[fnl][0].first][v[fnl][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p; int ans[301][301]; vector<pair<int, int>> kub[900001]; vector<int> kubb[900001]; int counter; int ind[90001][301]; int dist(pair<int, int>& a, pair<int, int>& b) { return abs(a.first - b.first) + abs(a.second - b.second); } pair<int, int> getL(int i, int l, int y) { if (!ind[i][l]) { return make_pair(0, 0); } int cc = ind[i][l]; if (!kubb[cc].size()) { return make_pair(0, 0); } if (kubb[cc][0] > y) { return make_pair(0, 0); } int p = 0; int q = kubb[cc].size() - 1; int s; while (p < q) { int s = (p + q + 1) / 2; if (kubb[cc][s] > y) { q = s - 1; } else { p = s; } } return make_pair(kubb[cc][p], l); } pair<int, int> getU(int i, int l, int y) { if (!ind[i][l]) { return make_pair(0, 0); } int cc = ind[i][l]; if (!kubb[cc].size()) { return make_pair(0, 0); } if (kubb[cc][kubb[cc].size() - 1] < y) { return make_pair(0, 0); } int p = 0; int q = kubb[cc].size() - 1; int s; while (p < q) { int s = (p + q) / 2; if (kubb[cc][s] < y) { p = s + 1; } else { q = s; } } return make_pair(kubb[cc][p], l); } int main() { ios_base::sync_with_stdio(0); cin >> n >> m >> p; int x; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { cin >> x; kub[x].push_back(make_pair(i, j)); if (!ind[x][j]) { ++counter; ind[x][j] = counter; } int cc = ind[x][j]; kubb[cc].push_back(i); sort(kubb[cc].begin(), kubb[cc].end()); } auto beg = make_pair(1, 1); for (int i = 0; i < kub[1].size(); ++i) { ans[kub[1][i].first][kub[1][i].second] = dist(kub[1][i], beg); } for (int i = 2; i <= p; ++i) for (int j = 0; j < kub[i].size(); ++j) { int x = kub[i][j].first; int y = kub[i][j].second; ans[x][y] = 2000123123; for (int l = 1; l <= m; ++l) { auto ptr1 = getL(i - 1, l, x); auto ptr2 = getU(i - 1, l, x); if (ptr1.first) { ans[x][y] = min(ans[x][y], ans[ptr1.first][ptr1.second] + dist(ptr1, kub[i][j])); } if (ptr2.first) { ans[x][y] = min(ans[x][y], ans[ptr2.first][ptr2.second] + dist(ptr2, kub[i][j])); } } } cout << ans[kub[p][0].first][kub[p][0].second] << endl; }
### Prompt Create a solution in Cpp for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, p; int ans[301][301]; vector<pair<int, int>> kub[900001]; vector<int> kubb[900001]; int counter; int ind[90001][301]; int dist(pair<int, int>& a, pair<int, int>& b) { return abs(a.first - b.first) + abs(a.second - b.second); } pair<int, int> getL(int i, int l, int y) { if (!ind[i][l]) { return make_pair(0, 0); } int cc = ind[i][l]; if (!kubb[cc].size()) { return make_pair(0, 0); } if (kubb[cc][0] > y) { return make_pair(0, 0); } int p = 0; int q = kubb[cc].size() - 1; int s; while (p < q) { int s = (p + q + 1) / 2; if (kubb[cc][s] > y) { q = s - 1; } else { p = s; } } return make_pair(kubb[cc][p], l); } pair<int, int> getU(int i, int l, int y) { if (!ind[i][l]) { return make_pair(0, 0); } int cc = ind[i][l]; if (!kubb[cc].size()) { return make_pair(0, 0); } if (kubb[cc][kubb[cc].size() - 1] < y) { return make_pair(0, 0); } int p = 0; int q = kubb[cc].size() - 1; int s; while (p < q) { int s = (p + q) / 2; if (kubb[cc][s] < y) { p = s + 1; } else { q = s; } } return make_pair(kubb[cc][p], l); } int main() { ios_base::sync_with_stdio(0); cin >> n >> m >> p; int x; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { cin >> x; kub[x].push_back(make_pair(i, j)); if (!ind[x][j]) { ++counter; ind[x][j] = counter; } int cc = ind[x][j]; kubb[cc].push_back(i); sort(kubb[cc].begin(), kubb[cc].end()); } auto beg = make_pair(1, 1); for (int i = 0; i < kub[1].size(); ++i) { ans[kub[1][i].first][kub[1][i].second] = dist(kub[1][i], beg); } for (int i = 2; i <= p; ++i) for (int j = 0; j < kub[i].size(); ++j) { int x = kub[i][j].first; int y = kub[i][j].second; ans[x][y] = 2000123123; for (int l = 1; l <= m; ++l) { auto ptr1 = getL(i - 1, l, x); auto ptr2 = getU(i - 1, l, x); if (ptr1.first) { ans[x][y] = min(ans[x][y], ans[ptr1.first][ptr1.second] + dist(ptr1, kub[i][j])); } if (ptr2.first) { ans[x][y] = min(ans[x][y], ans[ptr2.first][ptr2.second] + dist(ptr2, kub[i][j])); } } } cout << ans[kub[p][0].first][kub[p][0].second] << endl; } ```
#include <bits/stdc++.h> struct Point { int x, y; }; struct State { int x, y, dis; }; std::vector<Point> V[330 * 330]; int dp[330][330], n, m, p, a[330][330]; const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; bool vis[330][330]; State q[1000010]; bool cmp(Point &A, Point &B) { return dp[A.x][A.y] < dp[B.x][B.y]; } int abs(int x) { return x > 0 ? x : -x; } int dis(Point &A, Point &B) { return abs(A.x - B.x) + abs(A.y - B.y); } int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); V[a[i][j]].push_back((Point){i, j}); } for (int i = 0; i < V[1].size(); i++) dp[V[1][i].x][V[1][i].y] = V[1][i].x + V[1][i].y - 2; for (int i = 2; i <= p; i++) { int Size = V[i].size() * V[i - 1].size(); std::sort(V[i - 1].begin(), V[i - 1].end(), cmp); if (Size <= n * m) { for (int j = 0; j < V[i].size(); j++) { dp[V[i][j].x][V[i][j].y] = 2000000000; for (int k = 0; k < V[i - 1].size(); k++) { if (dp[V[i - 1][k].x][V[i - 1][k].y] >= dp[V[i][j].x][V[i][j].y]) break; dp[V[i][j].x][V[i][j].y] = std::min( dp[V[i][j].x][V[i][j].y], dp[V[i - 1][k].x][V[i - 1][k].y] + dis(V[i - 1][k], V[i][j])); } } } else { int op = 0, cl = 1; memset(vis, 0, sizeof vis); int tx = V[i - 1][0].x, ty = V[i - 1][0].y; vis[tx][ty] = 1; q[1] = (State){tx, ty, dp[tx][ty]}; int Lk = 1; while (op != cl) { State now = q[++op]; while (Lk < V[i - 1].size()) { int x = V[i - 1][Lk].x, y = V[i - 1][Lk].y; if (dp[x][y] > now.dis) break; q[++cl] = (State){x, y, dp[x][y]}; vis[x][y] = 1; Lk++; } for (int d = 0; d < 4; d++) { int x = now.x + dx[d], y = now.y + dy[d]; if (x < 1 || x > n || y < 1 || y > m || vis[x][y]) continue; vis[x][y] = 1; if (a[x][y] == i) dp[x][y] = now.dis + 1; q[++cl] = (State){x, y, now.dis + 1}; } } } } printf("%d", dp[V[p][0].x][V[p][0].y]); return 0; }
### Prompt Create a solution in CPP for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> struct Point { int x, y; }; struct State { int x, y, dis; }; std::vector<Point> V[330 * 330]; int dp[330][330], n, m, p, a[330][330]; const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; bool vis[330][330]; State q[1000010]; bool cmp(Point &A, Point &B) { return dp[A.x][A.y] < dp[B.x][B.y]; } int abs(int x) { return x > 0 ? x : -x; } int dis(Point &A, Point &B) { return abs(A.x - B.x) + abs(A.y - B.y); } int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); V[a[i][j]].push_back((Point){i, j}); } for (int i = 0; i < V[1].size(); i++) dp[V[1][i].x][V[1][i].y] = V[1][i].x + V[1][i].y - 2; for (int i = 2; i <= p; i++) { int Size = V[i].size() * V[i - 1].size(); std::sort(V[i - 1].begin(), V[i - 1].end(), cmp); if (Size <= n * m) { for (int j = 0; j < V[i].size(); j++) { dp[V[i][j].x][V[i][j].y] = 2000000000; for (int k = 0; k < V[i - 1].size(); k++) { if (dp[V[i - 1][k].x][V[i - 1][k].y] >= dp[V[i][j].x][V[i][j].y]) break; dp[V[i][j].x][V[i][j].y] = std::min( dp[V[i][j].x][V[i][j].y], dp[V[i - 1][k].x][V[i - 1][k].y] + dis(V[i - 1][k], V[i][j])); } } } else { int op = 0, cl = 1; memset(vis, 0, sizeof vis); int tx = V[i - 1][0].x, ty = V[i - 1][0].y; vis[tx][ty] = 1; q[1] = (State){tx, ty, dp[tx][ty]}; int Lk = 1; while (op != cl) { State now = q[++op]; while (Lk < V[i - 1].size()) { int x = V[i - 1][Lk].x, y = V[i - 1][Lk].y; if (dp[x][y] > now.dis) break; q[++cl] = (State){x, y, dp[x][y]}; vis[x][y] = 1; Lk++; } for (int d = 0; d < 4; d++) { int x = now.x + dx[d], y = now.y + dy[d]; if (x < 1 || x > n || y < 1 || y > m || vis[x][y]) continue; vis[x][y] = 1; if (a[x][y] == i) dp[x][y] = now.dis + 1; q[++cl] = (State){x, y, now.dis + 1}; } } } } printf("%d", dp[V[p][0].x][V[p][0].y]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; const int N = 500; const int P = N * N; const int DIFF = N + N; vector<int> x[P], y[P]; int n, m, p, a[N][N], dp[N][N], bfs[N][N]; int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; int abs(int x) { return x >= 0 ? x : -x; } void bfsSolve(int lvl) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) bfs[i][j] = -1; int minDist = INF; for (int i = 0; i < x[lvl - 1].size(); i++) minDist = min(minDist, dp[x[lvl - 1][i]][y[lvl - 1][i]]); vector<int> vx[DIFF], vy[DIFF]; for (int i = 0; i < x[lvl - 1].size(); i++) { int val = dp[x[lvl - 1][i]][y[lvl - 1][i]]; vx[val - minDist].push_back(x[lvl - 1][i]); vy[val - minDist].push_back(y[lvl - 1][i]); bfs[x[lvl - 1][i]][y[lvl - 1][i]] = val - minDist; } for (int i = 0; i < DIFF; i++) for (int j = 0; j < vx[i].size(); j++) for (int k = 0; k < 4; k++) { int tx = vx[i][j] + dx[k]; int ty = vy[i][j] + dy[k]; if (tx >= 0 && tx < n && ty >= 0 && ty < m && bfs[tx][ty] == -1) { bfs[tx][ty] = i + 1; vx[i + 1].push_back(tx); vy[i + 1].push_back(ty); } } for (int i = 0; i < x[lvl].size(); i++) dp[x[lvl][i]][y[lvl][i]] = minDist + bfs[x[lvl][i]][y[lvl][i]]; } void simpleSolve(int lvl) { for (int i = 0; i < x[lvl].size(); i++) { int tx = x[lvl][i]; int ty = y[lvl][i]; dp[tx][ty] = INF; for (int j = 0; j < x[lvl - 1].size(); j++) { int fx = x[lvl - 1][j]; int fy = y[lvl - 1][j]; dp[tx][ty] = min(dp[tx][ty], dp[fx][fy] + abs(tx - fx) + abs(ty - fy)); } } } int main() { cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> a[i][j]; x[a[i][j] - 1].push_back(i); y[a[i][j] - 1].push_back(j); } for (int i = 0; i < x[0].size(); i++) dp[x[0][i]][y[0][i]] = x[0][i] + y[0][i]; for (int i = 1; i < p; i++) if (x[i].size() * x[i - 1].size() >= n * m) bfsSolve(i); else simpleSolve(i); cout << dp[x[p - 1][0]][y[p - 1][0]] << endl; return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = 1e9; const int N = 500; const int P = N * N; const int DIFF = N + N; vector<int> x[P], y[P]; int n, m, p, a[N][N], dp[N][N], bfs[N][N]; int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; int abs(int x) { return x >= 0 ? x : -x; } void bfsSolve(int lvl) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) bfs[i][j] = -1; int minDist = INF; for (int i = 0; i < x[lvl - 1].size(); i++) minDist = min(minDist, dp[x[lvl - 1][i]][y[lvl - 1][i]]); vector<int> vx[DIFF], vy[DIFF]; for (int i = 0; i < x[lvl - 1].size(); i++) { int val = dp[x[lvl - 1][i]][y[lvl - 1][i]]; vx[val - minDist].push_back(x[lvl - 1][i]); vy[val - minDist].push_back(y[lvl - 1][i]); bfs[x[lvl - 1][i]][y[lvl - 1][i]] = val - minDist; } for (int i = 0; i < DIFF; i++) for (int j = 0; j < vx[i].size(); j++) for (int k = 0; k < 4; k++) { int tx = vx[i][j] + dx[k]; int ty = vy[i][j] + dy[k]; if (tx >= 0 && tx < n && ty >= 0 && ty < m && bfs[tx][ty] == -1) { bfs[tx][ty] = i + 1; vx[i + 1].push_back(tx); vy[i + 1].push_back(ty); } } for (int i = 0; i < x[lvl].size(); i++) dp[x[lvl][i]][y[lvl][i]] = minDist + bfs[x[lvl][i]][y[lvl][i]]; } void simpleSolve(int lvl) { for (int i = 0; i < x[lvl].size(); i++) { int tx = x[lvl][i]; int ty = y[lvl][i]; dp[tx][ty] = INF; for (int j = 0; j < x[lvl - 1].size(); j++) { int fx = x[lvl - 1][j]; int fy = y[lvl - 1][j]; dp[tx][ty] = min(dp[tx][ty], dp[fx][fy] + abs(tx - fx) + abs(ty - fy)); } } } int main() { cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> a[i][j]; x[a[i][j] - 1].push_back(i); y[a[i][j] - 1].push_back(j); } for (int i = 0; i < x[0].size(); i++) dp[x[0][i]][y[0][i]] = x[0][i] + y[0][i]; for (int i = 1; i < p; i++) if (x[i].size() * x[i - 1].size() >= n * m) bfsSolve(i); else simpleSolve(i); cout << dp[x[p - 1][0]][y[p - 1][0]] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p; int t[333][333]; vector<pair<int, int>> z[333 * 333]; long long d[333][333]; int rr[333][333]; long long rx[333][333]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> t[i][j]; z[t[i][j]].push_back({i, j}); d[i][j] = 99999999999999999LL; if (t[i][j] == 1) d[i][j] = abs(i - 1) + abs(j - 1); } } for (int i = 1; i <= p - 1; i++) { int s = z[i].size(); if (s * s <= 3 * n * m) { for (int j = 0; j < z[i].size(); j++) { int y = z[i][j].first; int x = z[i][j].second; for (int e = 0; e < z[i + 1].size(); e++) { int uy = z[i + 1][e].first; int ux = z[i + 1][e].second; d[uy][ux] = min(d[uy][ux], d[y][x] + abs(y - uy) + abs(x - ux)); } } } else { vector<pair<long long, int>> u; for (int j = 0; j < z[i].size(); j++) { long long k = d[z[i][j].first][z[i][j].second]; u.push_back({k, j}); } sort(u.begin(), u.end()); vector<pair<int, int>> w; int ay = z[i][u[0].second].first; int ax = z[i][u[0].second].second; w.push_back({ay, ax}); rr[ay][ax] = i; rx[ay][ax] = u[0].first; int k = 0; for (int j = 0; j < w.size(); j++) { int uy = w[j].first; int ux = w[j].second; long long ud = rx[uy][ux]; while (k + 1 < u.size() && u[k + 1].first == ud) { int ty = z[i][u[k + 1].second].first; int tx = z[i][u[k + 1].second].second; if (rr[ty][tx] != i || rx[ty][tx] > ud) { w.push_back({ty, tx}); rr[ty][tx] = i; rx[ty][tx] = ud; } k++; } int f[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for (int k = 0; k < 4; k++) { int fy = uy + f[k][0]; int fx = ux + f[k][1]; if (fy < 1 || fy > n || fx < 1 || fx > m) continue; if (rr[fy][fx] == i && rx[fy][fx] <= ud + 1) continue; w.push_back({fy, fx}); rr[fy][fx] = i; rx[fy][fx] = ud + 1; if (t[fy][fx] == i + 1) d[fy][fx] = ud + 1; } } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (t[i][j] == p) { cout << d[i][j] << "\n"; return 0; } } } }
### Prompt Please formulate a Cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, p; int t[333][333]; vector<pair<int, int>> z[333 * 333]; long long d[333][333]; int rr[333][333]; long long rx[333][333]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> t[i][j]; z[t[i][j]].push_back({i, j}); d[i][j] = 99999999999999999LL; if (t[i][j] == 1) d[i][j] = abs(i - 1) + abs(j - 1); } } for (int i = 1; i <= p - 1; i++) { int s = z[i].size(); if (s * s <= 3 * n * m) { for (int j = 0; j < z[i].size(); j++) { int y = z[i][j].first; int x = z[i][j].second; for (int e = 0; e < z[i + 1].size(); e++) { int uy = z[i + 1][e].first; int ux = z[i + 1][e].second; d[uy][ux] = min(d[uy][ux], d[y][x] + abs(y - uy) + abs(x - ux)); } } } else { vector<pair<long long, int>> u; for (int j = 0; j < z[i].size(); j++) { long long k = d[z[i][j].first][z[i][j].second]; u.push_back({k, j}); } sort(u.begin(), u.end()); vector<pair<int, int>> w; int ay = z[i][u[0].second].first; int ax = z[i][u[0].second].second; w.push_back({ay, ax}); rr[ay][ax] = i; rx[ay][ax] = u[0].first; int k = 0; for (int j = 0; j < w.size(); j++) { int uy = w[j].first; int ux = w[j].second; long long ud = rx[uy][ux]; while (k + 1 < u.size() && u[k + 1].first == ud) { int ty = z[i][u[k + 1].second].first; int tx = z[i][u[k + 1].second].second; if (rr[ty][tx] != i || rx[ty][tx] > ud) { w.push_back({ty, tx}); rr[ty][tx] = i; rx[ty][tx] = ud; } k++; } int f[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for (int k = 0; k < 4; k++) { int fy = uy + f[k][0]; int fx = ux + f[k][1]; if (fy < 1 || fy > n || fx < 1 || fx > m) continue; if (rr[fy][fx] == i && rx[fy][fx] <= ud + 1) continue; w.push_back({fy, fx}); rr[fy][fx] = i; rx[fy][fx] = ud + 1; if (t[fy][fx] == i + 1) d[fy][fx] = ud + 1; } } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (t[i][j] == p) { cout << d[i][j] << "\n"; return 0; } } } } ```
#include <bits/stdc++.h> using namespace std; struct node { int dis, pos; } b[3050000], now; int a[310][310]; int dp[310][310]; bool cmp(node a, node b) { return a.dis < b.dis; } vector<node> mp[310 * 310]; int main() { int n, m, p; scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) dp[i][j] = 0x3f3f3f3f; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) { dp[i][j] = i + j - 2; now.dis = dp[i][j]; } now.pos = (i - 1) * m + j; mp[a[i][j]].push_back(now); } } sort(mp[1].begin(), mp[1].end(), cmp); for (int i = 2; i <= p; i++) { int sz1 = mp[i].size(); int sz2 = mp[i - 1].size(); for (int j = 0; j < sz1; j++) { int x = mp[i][j].pos / m + 1; int y = mp[i][j].pos % m; if (y == 0) y = m, x--; for (int k = 0; k < sz2 && k < 1000; k++) { int xx = mp[i - 1][k].pos / m + 1; int yy = mp[i - 1][k].pos % m; if (yy == 0) yy = m, xx--; dp[x][y] = min(dp[x][y], dp[xx][yy] + abs(x - xx) + abs(y - yy)); } mp[i][j].dis = dp[x][y]; } sort(mp[i].begin(), mp[i].end(), cmp); } int ans = 0x3f3f3f3f; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (a[i][j] == p) ans = min(dp[i][j], ans); } printf("%d\n", ans); return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct node { int dis, pos; } b[3050000], now; int a[310][310]; int dp[310][310]; bool cmp(node a, node b) { return a.dis < b.dis; } vector<node> mp[310 * 310]; int main() { int n, m, p; scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) dp[i][j] = 0x3f3f3f3f; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) { dp[i][j] = i + j - 2; now.dis = dp[i][j]; } now.pos = (i - 1) * m + j; mp[a[i][j]].push_back(now); } } sort(mp[1].begin(), mp[1].end(), cmp); for (int i = 2; i <= p; i++) { int sz1 = mp[i].size(); int sz2 = mp[i - 1].size(); for (int j = 0; j < sz1; j++) { int x = mp[i][j].pos / m + 1; int y = mp[i][j].pos % m; if (y == 0) y = m, x--; for (int k = 0; k < sz2 && k < 1000; k++) { int xx = mp[i - 1][k].pos / m + 1; int yy = mp[i - 1][k].pos % m; if (yy == 0) yy = m, xx--; dp[x][y] = min(dp[x][y], dp[xx][yy] + abs(x - xx) + abs(y - yy)); } mp[i][j].dis = dp[x][y]; } sort(mp[i].begin(), mp[i].end(), cmp); } int ans = 0x3f3f3f3f; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (a[i][j] == p) ans = min(dp[i][j], ans); } printf("%d\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 305; int n, m, p; int dp[N][N], visited[N][N], specialdp[N][N]; map<int, vector<pair<int, int> > > color; struct node { int r, c, cost; bool operator<(const node &t) const { return cost < t.cost; } }; bool open(int r, int c) { if (r < 1 || c < 1 || r > n || c > m) return false; if (visited[r][c]) return false; visited[r][c] = true; return true; } void special(int c) { memset(visited, 0, sizeof(visited)); memset(specialdp, 0x3f, sizeof(specialdp)); vector<node> initial; for (auto a : color[c]) { initial.push_back({a.first, a.second, dp[a.first][a.second]}); visited[a.first][a.second] = true; } sort(initial.begin(), initial.end()); int l = 1; vector<node> bfs(1, initial[0]); for (int i = 0; i < bfs.size(); ++i) { node cur = bfs[i]; while (l < initial.size() && initial[l].cost <= cur.cost + 1) { open(initial[l].r, initial[l].c); bfs.push_back(initial[l++]); } specialdp[cur.r][cur.c] = cur.cost; if (open(cur.r - 1, cur.c)) bfs.push_back({cur.r - 1, cur.c, cur.cost + 1}); if (open(cur.r + 1, cur.c)) bfs.push_back({cur.r + 1, cur.c, cur.cost + 1}); if (open(cur.r, cur.c + 1)) bfs.push_back({cur.r, cur.c + 1, cur.cost + 1}); if (open(cur.r, cur.c - 1)) bfs.push_back({cur.r, cur.c - 1, cur.cost + 1}); } for (auto a : color[c + 1]) dp[a.first][a.second] = specialdp[a.first][a.second]; } int main() { memset(dp, 0x3f, sizeof(dp)); cin >> n >> m >> p; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { int c; scanf("%d", &c); color[c].push_back({i, j}); if (c == 1) dp[i][j] = i + j - 2; } for (int i = 1; i <= p; ++i) { if (color[i].size() * color[i + 1].size() > n * n) { special(i); } else { for (auto a : color[i]) for (auto b : color[i + 1]) dp[b.first][b.second] = min(dp[b.first][b.second], dp[a.first][a.second] + abs(a.first - b.first) + abs(a.second - b.second)); } } int ans = 1e9; for (auto a : color[p]) ans = min(ans, dp[a.first][a.second]); cout << ans << '\n'; }
### Prompt In cpp, your task is to solve the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 305; int n, m, p; int dp[N][N], visited[N][N], specialdp[N][N]; map<int, vector<pair<int, int> > > color; struct node { int r, c, cost; bool operator<(const node &t) const { return cost < t.cost; } }; bool open(int r, int c) { if (r < 1 || c < 1 || r > n || c > m) return false; if (visited[r][c]) return false; visited[r][c] = true; return true; } void special(int c) { memset(visited, 0, sizeof(visited)); memset(specialdp, 0x3f, sizeof(specialdp)); vector<node> initial; for (auto a : color[c]) { initial.push_back({a.first, a.second, dp[a.first][a.second]}); visited[a.first][a.second] = true; } sort(initial.begin(), initial.end()); int l = 1; vector<node> bfs(1, initial[0]); for (int i = 0; i < bfs.size(); ++i) { node cur = bfs[i]; while (l < initial.size() && initial[l].cost <= cur.cost + 1) { open(initial[l].r, initial[l].c); bfs.push_back(initial[l++]); } specialdp[cur.r][cur.c] = cur.cost; if (open(cur.r - 1, cur.c)) bfs.push_back({cur.r - 1, cur.c, cur.cost + 1}); if (open(cur.r + 1, cur.c)) bfs.push_back({cur.r + 1, cur.c, cur.cost + 1}); if (open(cur.r, cur.c + 1)) bfs.push_back({cur.r, cur.c + 1, cur.cost + 1}); if (open(cur.r, cur.c - 1)) bfs.push_back({cur.r, cur.c - 1, cur.cost + 1}); } for (auto a : color[c + 1]) dp[a.first][a.second] = specialdp[a.first][a.second]; } int main() { memset(dp, 0x3f, sizeof(dp)); cin >> n >> m >> p; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { int c; scanf("%d", &c); color[c].push_back({i, j}); if (c == 1) dp[i][j] = i + j - 2; } for (int i = 1; i <= p; ++i) { if (color[i].size() * color[i + 1].size() > n * n) { special(i); } else { for (auto a : color[i]) for (auto b : color[i + 1]) dp[b.first][b.second] = min(dp[b.first][b.second], dp[a.first][a.second] + abs(a.first - b.first) + abs(a.second - b.second)); } } int ans = 1e9; for (auto a : color[p]) ans = min(ans, dp[a.first][a.second]); cout << ans << '\n'; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p, k, a; vector<pair<int, int> > G[90002]; int dp[2][302][302]; int main() { memset(dp[1], -1, sizeof(dp[1])); cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { cin >> a; G[a].push_back({i, j}); if (a == 1) dp[1][i][j] = i + j - 2; } for (int i = 2; i <= p; i++) { memset(dp[i % 2], -1, sizeof(dp[i % 2])); for (auto it : G[i - 1]) { int x = it.first; int y = it.second; for (int j = 1; j <= m; j++) if (dp[1 - i % 2][x][j] == -1) dp[1 - i % 2][x][j] = dp[1 - i % 2][x][y] + abs(y - j); else dp[1 - i % 2][x][j] = min(dp[1 - i % 2][x][j], dp[1 - i % 2][x][y] + abs(y - j)); } for (auto it : G[i]) { int x = it.first; int y = it.second; for (int j = 1; j <= n; j++) if (dp[1 - i % 2][j][y] != -1) { if (dp[i % 2][x][y] != -1) dp[i % 2][x][y] = min(dp[i % 2][x][y], dp[1 - i % 2][j][y] + abs(x - j)); else dp[i % 2][x][y] = dp[1 - i % 2][j][y] + abs(x - j); } } } cout << dp[p % 2][G[p][0].first][G[p][0].second]; return 0; }
### Prompt Generate a cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, p, k, a; vector<pair<int, int> > G[90002]; int dp[2][302][302]; int main() { memset(dp[1], -1, sizeof(dp[1])); cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { cin >> a; G[a].push_back({i, j}); if (a == 1) dp[1][i][j] = i + j - 2; } for (int i = 2; i <= p; i++) { memset(dp[i % 2], -1, sizeof(dp[i % 2])); for (auto it : G[i - 1]) { int x = it.first; int y = it.second; for (int j = 1; j <= m; j++) if (dp[1 - i % 2][x][j] == -1) dp[1 - i % 2][x][j] = dp[1 - i % 2][x][y] + abs(y - j); else dp[1 - i % 2][x][j] = min(dp[1 - i % 2][x][j], dp[1 - i % 2][x][y] + abs(y - j)); } for (auto it : G[i]) { int x = it.first; int y = it.second; for (int j = 1; j <= n; j++) if (dp[1 - i % 2][j][y] != -1) { if (dp[i % 2][x][y] != -1) dp[i % 2][x][y] = min(dp[i % 2][x][y], dp[1 - i % 2][j][y] + abs(x - j)); else dp[i % 2][x][y] = dp[1 - i % 2][j][y] + abs(x - j); } } } cout << dp[p % 2][G[p][0].first][G[p][0].second]; return 0; } ```
#include <bits/stdc++.h> using namespace std; int ar[305][305]; vector<int> col[305]; int dp[305][305]; vector<pair<int, int> > poss[90005]; bool vis[305]; int n, m, p; void pr() {} int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { scanf("%d", &ar[i][j]); if (ar[i][j] == 1) dp[i][j] = j + i; else dp[i][j] = 1e9; poss[ar[i][j]].push_back(make_pair(i, j)); } pr(); for (int val = 1; val <= p - 1; ++val) { for (int i = 0; i < max(m, n); ++i) { col[i].clear(); vis[i] = false; } for (pair<int, int> p : poss[val + 1]) { int i = p.first; int j = p.second; col[j].push_back(i); } for (pair<int, int> p : poss[val]) vis[p.first] = true; for (int y = 0; y < n; ++y) if (vis[y]) { int best = 1e9; for (int x = 0; x < m; ++x) { ++best; if (ar[y][x] == val) best = min(best, dp[y][x]); for (int he : col[x]) dp[he][x] = min(dp[he][x], best + abs(he - y)); } best = 1e9; for (int x = m - 1; x >= 0; --x) { ++best; if (ar[y][x] == val) best = min(best, dp[y][x]); for (int he : col[x]) dp[he][x] = min(dp[he][x], best + abs(he - y)); } } pr(); } for (int x = 0; x < m; ++x) for (int y = 0; y < n; ++y) if (ar[y][x] == p) printf("%d\n", dp[y][x]); return 0; }
### Prompt Your task is to create a CPP solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int ar[305][305]; vector<int> col[305]; int dp[305][305]; vector<pair<int, int> > poss[90005]; bool vis[305]; int n, m, p; void pr() {} int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { scanf("%d", &ar[i][j]); if (ar[i][j] == 1) dp[i][j] = j + i; else dp[i][j] = 1e9; poss[ar[i][j]].push_back(make_pair(i, j)); } pr(); for (int val = 1; val <= p - 1; ++val) { for (int i = 0; i < max(m, n); ++i) { col[i].clear(); vis[i] = false; } for (pair<int, int> p : poss[val + 1]) { int i = p.first; int j = p.second; col[j].push_back(i); } for (pair<int, int> p : poss[val]) vis[p.first] = true; for (int y = 0; y < n; ++y) if (vis[y]) { int best = 1e9; for (int x = 0; x < m; ++x) { ++best; if (ar[y][x] == val) best = min(best, dp[y][x]); for (int he : col[x]) dp[he][x] = min(dp[he][x], best + abs(he - y)); } best = 1e9; for (int x = m - 1; x >= 0; --x) { ++best; if (ar[y][x] == val) best = min(best, dp[y][x]); for (int he : col[x]) dp[he][x] = min(dp[he][x], best + abs(he - y)); } } pr(); } for (int x = 0; x < m; ++x) for (int y = 0; y < n; ++y) if (ar[y][x] == p) printf("%d\n", dp[y][x]); return 0; } ```
#include <bits/stdc++.h> typedef long long LL; const double INF = 1e100; const int oo = ~0u >> 2; const double pi = acos(-1.0); const double EPS = 1e-8; const int MAXN = 100033; int dp[303][303]; int map[303][303]; std::vector<std::pair<int, int> > s[90003]; std::vector<int> c[303]; int vis[303]; int n, m, p; int main() { scanf("%d%d%d", &n, &m, &p); for (int i = (1), __ = (n); i <= __; ++i) for (int j = (1), __ = (m); j <= __; ++j) { scanf("%d", &map[i][j]); if (map[i][j] == 1) dp[i][j] = i + j - 2; else dp[i][j] = oo; s[map[i][j]].push_back(std::pair<int, int>(i, j)); } for (int v = (1), __ = (p - 1); v <= __; ++v) { for (int i = (1), __ = (std::max(n, m)); i <= __; ++i) { vis[i] = 0; c[i].clear(); } for (int i = (0), __ = (s[v + 1].size()); i < __; ++i) { c[s[v + 1][i].second].push_back(s[v + 1][i].first); } for (int i = (0), __ = (s[v].size()); i < __; ++i) vis[s[v][i].first] = 1; for (int i = (1), __ = (n); i <= __; ++i) if (vis[i]) { int res = oo; for (int j = (1), __ = (m); j <= __; ++j) { ++res; if (map[i][j] == v) { res = std::min(res, dp[i][j]); } for (int k = (0), __ = (c[j].size()); k < __; ++k) dp[c[j][k]][j] = std::min(dp[c[j][k]][j], res + abs(i - c[j][k])); } res = oo; for (int j = (m), __ = (1); j >= __; --j) { ++res; if (map[i][j] == v) { res = std::min(res, dp[i][j]); } for (int k = (0), __ = (c[j].size()); k < __; ++k) dp[c[j][k]][j] = std::min(dp[c[j][k]][j], res + abs(i - c[j][k])); } } } for (int i = (1), __ = (n); i <= __; ++i) for (int j = (1), __ = (m); j <= __; ++j) if (map[i][j] == p) printf("%d\n", dp[i][j]); return 0; }
### Prompt Please create a solution in Cpp to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> typedef long long LL; const double INF = 1e100; const int oo = ~0u >> 2; const double pi = acos(-1.0); const double EPS = 1e-8; const int MAXN = 100033; int dp[303][303]; int map[303][303]; std::vector<std::pair<int, int> > s[90003]; std::vector<int> c[303]; int vis[303]; int n, m, p; int main() { scanf("%d%d%d", &n, &m, &p); for (int i = (1), __ = (n); i <= __; ++i) for (int j = (1), __ = (m); j <= __; ++j) { scanf("%d", &map[i][j]); if (map[i][j] == 1) dp[i][j] = i + j - 2; else dp[i][j] = oo; s[map[i][j]].push_back(std::pair<int, int>(i, j)); } for (int v = (1), __ = (p - 1); v <= __; ++v) { for (int i = (1), __ = (std::max(n, m)); i <= __; ++i) { vis[i] = 0; c[i].clear(); } for (int i = (0), __ = (s[v + 1].size()); i < __; ++i) { c[s[v + 1][i].second].push_back(s[v + 1][i].first); } for (int i = (0), __ = (s[v].size()); i < __; ++i) vis[s[v][i].first] = 1; for (int i = (1), __ = (n); i <= __; ++i) if (vis[i]) { int res = oo; for (int j = (1), __ = (m); j <= __; ++j) { ++res; if (map[i][j] == v) { res = std::min(res, dp[i][j]); } for (int k = (0), __ = (c[j].size()); k < __; ++k) dp[c[j][k]][j] = std::min(dp[c[j][k]][j], res + abs(i - c[j][k])); } res = oo; for (int j = (m), __ = (1); j >= __; --j) { ++res; if (map[i][j] == v) { res = std::min(res, dp[i][j]); } for (int k = (0), __ = (c[j].size()); k < __; ++k) dp[c[j][k]][j] = std::min(dp[c[j][k]][j], res + abs(i - c[j][k])); } } } for (int i = (1), __ = (n); i <= __; ++i) for (int j = (1), __ = (m); j <= __; ++j) if (map[i][j] == p) printf("%d\n", dp[i][j]); return 0; } ```
#include <bits/stdc++.h> using namespace std; template <typename T> inline T SQR(T x) { return x * x; } template <typename T> inline T MIN(T x, T y) { return (x < y) ? x : y; } template <typename T> inline T MAX(T x, T y) { return (x > y) ? x : y; } template <typename T> inline T ABS(T x) { return (x > 0) ? x : -x; } template <typename T> inline void UPDATE_MIN(T &x, T y) { if (y < x) { x = y; } } template <typename T> inline void UPDATE_MAX(T &x, T y) { if (x < y) { x = y; } } template <typename T> inline int ARGMAX(T cont) { return max_element(cont.begin(), cont.end()) - cont.begin(); } template <typename T> inline int ARGMIN(T cont) { return min_element(cont.begin(), cont.end()) - cont.begin(); } vector<string> split(const string &s, char c) { vector<string> v; stringstream ss(s); string x; while (getline(ss, x, c)) v.emplace_back(x); return move(v); } template <typename T, typename... Args> inline string arrStr(T arr, int n) { stringstream s; s << "["; for (__typeof(n - 1) i = (0), __tmpvar__end87 = (n - 1); i < __tmpvar__end87; i++) s << arr[i] << ","; s << arr[n - 1] << "]"; return s.str(); } template <class T> inline string TOSTR(const T &x) { stringstream ss; ss << x; return ss.str(); } inline void PR(void) {} inline void PR(int x) { printf("%d", x); } inline void PR(long long x) { printf("%lld", x); } inline void PR(char *s) { printf("%s", s); } inline void PR(const char *s) { printf("%s", s); } inline void PR(double f) { printf("%.10lf", f); } inline void PR(long double f) { printf("%.10llf", f); } inline void PR(vector<int> &vec) { for (auto x : vec) { PR(x); putc(0x20, stdout); } } template <typename T> inline void PRS(T x) { PR(x); putc(0x20, stdout); } template <typename T> inline void PRN(T x) { PR(x); putc(0x0a, stdout); } void PRN(void) { putc(0x0a, stdout); } inline int gcd(int a, int b) { return a ? gcd(b % a, a) : b; } inline long long gcd(long long a, long long b) { return a ? gcd(b % a, a) : b; } inline long long powmod(long long a, long long p, long long m) { long long r = 1; while (p) { if (p & 1) r = r * a % m; p >>= 1; a = a * a % m; } return r; } struct pairhash { template <typename T, typename U> std::size_t operator()(const std::pair<T, U> &x) const { return std::hash<T>()(x.first) ^ std::hash<U>()(x.second); } }; template <typename K, typename V> V GetWithDef(const std::map<K, V> &m, const K &key, const V &defval) { auto it = m.find(key); return (it == m.end()) ? defval : it->second; } template <typename K, typename V> void SetDef(std::map<K, V> &m, const K &key, const V &defval) { auto it = m.find(key); if (it == m.end()) m[key] = defval; } template <typename K, typename V> V GetWithDef(const std::unordered_map<K, V> &m, const K &key, const V &defval) { auto it = m.find(key); return (it == m.end()) ? defval : it->second; } template <typename K, typename V> void SetDef(std::unordered_map<K, V> &m, const K &key, const V &defval) { auto it = m.find(key); if (it == m.end()) m[key] = defval; } const int MOD = 1000 * 1000 * 1000 + 7; const double PI = 3.1415926535897932384626433832795l; inline void addto(int &a, int b) { a += b; if (a >= MOD) a -= MOD; } inline int add(int a, int b) { a += b; if (a >= MOD) a -= MOD; return a; } inline void subto(int &a, int b) { a -= b; if (a < 0) a += MOD; if (a >= MOD) a -= MOD; } inline int sub(int a, int b) { a -= b; if (a < 0) a += MOD; if (a >= MOD) a -= MOD; return a; } inline void multo(int &a, int b) { a = (long long)a * b % MOD; } inline int mul(int a, int b) { return (long long)a * b % MOD; } inline int mulmod(int a, int b, int mod) { return (long long)a * b % mod; } inline int powmod(int a, int e, int mod) { int x; for (x = 1; e > 0; e >>= 1) { if (e & 1) x = mulmod(x, a, mod); a = mulmod(a, a, mod); } return x; } inline int invmod_prime(int a, int mod) { return powmod(a, mod - 2, mod); } inline long long invmod_LL(long long p) { long long q = p; for (long long a = p * p; a != 1; a *= a) q *= a; return q; } const int ZERO = 1e9; struct Node; Node *allocNode(int l, int r); struct Node { int my_l, my_r; Node *pleft = NULL; Node *pright = NULL; int my_val; int my_lazy; Node() {} inline bool inside(int l, int r) { return (l <= my_l) && (my_r <= r); } inline bool outside(int l, int r) { return (r < my_l) || (l > my_r); } inline bool single() { return (my_l == my_r); } inline int length() { return (my_r - my_l + 1); } inline void check_fork() { if (pleft) return; assert(!single()); pleft = allocNode(my_l, (my_l + my_r) / 2); pright = allocNode((my_l + my_r) / 2 + 1, my_r); } inline Node *left() { check_fork(); return pleft; } inline Node *right() { check_fork(); return pright; } void clear() { if (pleft) { pleft->clear(); delete pleft; } if (pright) { pright->clear(); delete pright; } } inline static int combine(int a, int b) { return min(a, b); } int sum_range(int l, int r) { push(); if (outside(l, r)) return ZERO; if (inside(l, r)) return my_val; return combine(left()->sum_range(l, r), right()->sum_range(l, r)); } int get_single(int l) { return sum_range(l, l); } void set_single(int x, int new_val) { push(); if (outside(x, x)) return; if ((my_l == my_r) && (my_l == x)) { my_val = new_val; return; } left()->set_single(x, new_val); right()->set_single(x, new_val); my_val = combine(left()->my_val, right()->my_val); } void modify_single(int x, int new_val) { push(); if (outside(x, x)) return; if ((my_l == my_r) && (my_l == x)) { my_val = combine(my_val, new_val); return; } left()->modify_single(x, new_val); right()->modify_single(x, new_val); my_val = combine(left()->my_val, right()->my_val); } void modify_range(int l, int r, int new_val) { push(); if (outside(l, r)) return; if (inside(l, r)) { my_lazy = combine(my_lazy, new_val); return; } left()->modify_range(l, r, new_val); right()->modify_range(l, r, new_val); my_val = combine(left()->my_val, right()->my_val); } void push() { return; if (!single()) { left()->my_lazy = combine(left()->my_lazy, my_lazy); right()->my_lazy = combine(right()->my_lazy, my_lazy); } my_val = combine(my_val, my_lazy); my_lazy = ZERO; } }; struct WideNode; WideNode *allocWideNode(int l, int r, int l2, int r2); struct WideNode { int my_l, my_r; WideNode *pleft = NULL; WideNode *pright = NULL; Node *my_val = NULL; WideNode() {} inline bool inside(int l, int r) { return (l <= my_l) && (my_r <= r); } inline bool outside(int l, int r) { return (r < my_l) || (l > my_r); } inline bool single() { return (my_l == my_r); } inline int length() { return (my_r - my_l + 1); } inline void check_fork() { if (pleft) return; assert(!single()); pleft = allocWideNode(my_l, (my_l + my_r) / 2, my_val->my_l, my_val->my_r); pright = allocWideNode((my_l + my_r) / 2 + 1, my_r, my_val->my_l, my_val->my_r); } inline WideNode *left() { check_fork(); return pleft; } inline WideNode *right() { check_fork(); return pright; } void clear() { if (pleft) { pleft->clear(); delete pleft; } if (pright) { pright->clear(); delete pright; } my_val->clear(); } int sum_range(int l, int r, int l2, int r2) { if (outside(l, r)) return ZERO; if (inside(l, r)) return my_val->sum_range(l2, r2); return Node::combine(left()->sum_range(l, r, l2, r2), right()->sum_range(l, r, l2, r2)); } int get_single(int l, int l2) { return sum_range(l, l, l2, l2); } void set_single(int x, int y, int new_val) { if (outside(x, x)) return; if ((my_l == my_r) && (my_l == x)) { my_val->set_single(y, new_val); return; } left()->set_single(x, y, new_val); right()->set_single(x, y, new_val); my_val->modify_single(y, new_val); } void modify_single(int x, int y, int new_val) { if (outside(x, x)) return; if ((my_l == my_r) && (my_l == x)) { my_val->set_single(y, Node::combine(my_val->get_single(y), new_val)); return; } left()->modify_single(x, y, new_val); right()->modify_single(x, y, new_val); merge_at(y); } void merge_at(int y) { my_val->set_single(y, Node::combine(left()->my_val->get_single(y), right()->my_val->get_single(y))); } }; Node memNode[5123123]; int ptrNode = 0; Node *allocNode(int l, int r) { Node &node = memNode[ptrNode++]; assert(ptrNode < 5123123); node.my_l = l; node.my_r = r; node.my_val = ZERO; node.my_lazy = ZERO; node.pleft = NULL; node.pright = NULL; return &node; } WideNode memWideNode[123123]; int ptrWideNode = 0; WideNode *allocWideNode(int l, int r, int l2, int r2) { WideNode &node = memWideNode[ptrWideNode++]; assert(ptrWideNode < 123123); node.my_l = l; node.my_r = r; node.my_val = allocNode(l2, r2); node.pleft = NULL; node.pright = NULL; return &node; } int N, M, K, L, E, Q, P, SY, SX; int arr[301] = {}; int mp[301][301] = {}; int mp_rot[4][301][301] = {}; vector<pair<int, int>> by_val[301 * 301]; int min_dist[500][500] = {}; int cx; int cy; bool funcless(pair<int, int> yx1, pair<int, int> yx2) { int y1 = yx1.first; int x1 = yx1.second; int y2 = yx2.first; int x2 = yx2.second; return abs(cx - x1) + abs(cy - y1) < abs(cx - x2) + abs(cy - y2); } inline void rotate90cw(int &y, int &x, int sy, int sx) { int x2 = sy - 1 - y; y = x; x = x2; } template <typename T> void rotate90cw(T src[301][301], T dst[301][301], int sy, int sx) { for (__typeof(sx) x = (0), __tmpvar__end475 = (sx); x < __tmpvar__end475; x++) { for (__typeof(sy) y = (0), __tmpvar__end476 = (sy); y < __tmpvar__end476; y++) { int y2 = x; int x2 = sy - 1 - y; dst[y2][x2] = src[y][x]; } } } int main() { ios_base::sync_with_stdio(0); scanf("%d%d%d", &SY, &SX, &P); for (__typeof(SY) y = (0), __tmpvar__end491 = (SY); y < __tmpvar__end491; y++) { for (__typeof(SX) x = (0), __tmpvar__end492 = (SX); x < __tmpvar__end492; x++) { scanf("%d", &mp[y][x]); by_val[mp[y][x]].push_back(make_pair(y, x)); min_dist[y][x] = 1e9; } } rotate90cw(mp, mp_rot[0], SY, SX); rotate90cw(mp_rot[0], mp_rot[1], SX, SY); rotate90cw(mp_rot[1], mp_rot[2], SY, SX); rotate90cw(mp_rot[2], mp_rot[3], SX, SY); rotate90cw(mp_rot[3], mp_rot[0], SY, SX); int ans = 1e9; for (auto &yx : by_val[1]) { int y = yx.first; int x = yx.second; min_dist[y][x] = y + x; if (P == 1) UPDATE_MIN(ans, x + y); } for (__typeof(P) val = (1), __tmpvar__end510 = (P); val < __tmpvar__end510; val++) { 1; WideNode *nodes[4] = { allocWideNode(0, 301, 0, 301), allocWideNode(0, 301, 0, 301), allocWideNode(0, 301, 0, 301), allocWideNode(0, 301, 0, 301)}; for (auto &yx : by_val[val]) { int y = yx.first; int x = yx.second; int dist = min_dist[y][x]; int sy = SY; int sx = SX; for (__typeof(4) r = (0), __tmpvar__end521 = (4); r < __tmpvar__end521; r++) { nodes[r]->set_single(x, y, dist + x + y); rotate90cw(y, x, sy, sx); swap(sy, sx); } } for (auto &yx2 : by_val[val + 1]) { int y2 = yx2.first; int x2 = yx2.second; int sy = SY; int sx = SX; int xorig = x2; int yorig = y2; for (__typeof(4) r = (0), __tmpvar__end536 = (4); r < __tmpvar__end536; r++) { int dist2 = nodes[r]->sum_range(x2, sx, y2, sy) - x2 - y2; UPDATE_MIN(min_dist[yorig][xorig], dist2); if (val + 1 == P) UPDATE_MIN(ans, dist2); rotate90cw(y2, x2, sy, sx); swap(sy, sx); } } ptrNode = 0; ptrWideNode = 0; 1; } PRN(ans); return 0; priority_queue<pair<int, pair<int, int>>> pq; for (auto &yx : by_val[1]) { int y = yx.first; int x = yx.second; int dist = y + x; pq.push(make_pair(-dist, yx)); min_dist[y][x] = dist; 1; } while (!pq.empty()) { auto s = pq.top(); pq.pop(); int dist = -s.first; if (dist >= ans) break; int y = s.second.first; int x = s.second.second; if (dist != min_dist[y][x]) continue; int val = mp[y][x]; for (auto &yx2 : by_val[val + 1]) { int y2 = yx2.first; int x2 = yx2.second; int dist2 = dist + abs(y2 - y) + abs(x2 - x); int val2 = mp[y2][x2]; 1; if (val2 == P) UPDATE_MIN(ans, dist2); else if (dist2 < ans && dist2 < min_dist[y2][x2]) { min_dist[y2][x2] = dist2; pq.push(make_pair(-dist2, yx2)); } } } PRN(ans); return 0; }
### Prompt Generate a Cpp solution to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T> inline T SQR(T x) { return x * x; } template <typename T> inline T MIN(T x, T y) { return (x < y) ? x : y; } template <typename T> inline T MAX(T x, T y) { return (x > y) ? x : y; } template <typename T> inline T ABS(T x) { return (x > 0) ? x : -x; } template <typename T> inline void UPDATE_MIN(T &x, T y) { if (y < x) { x = y; } } template <typename T> inline void UPDATE_MAX(T &x, T y) { if (x < y) { x = y; } } template <typename T> inline int ARGMAX(T cont) { return max_element(cont.begin(), cont.end()) - cont.begin(); } template <typename T> inline int ARGMIN(T cont) { return min_element(cont.begin(), cont.end()) - cont.begin(); } vector<string> split(const string &s, char c) { vector<string> v; stringstream ss(s); string x; while (getline(ss, x, c)) v.emplace_back(x); return move(v); } template <typename T, typename... Args> inline string arrStr(T arr, int n) { stringstream s; s << "["; for (__typeof(n - 1) i = (0), __tmpvar__end87 = (n - 1); i < __tmpvar__end87; i++) s << arr[i] << ","; s << arr[n - 1] << "]"; return s.str(); } template <class T> inline string TOSTR(const T &x) { stringstream ss; ss << x; return ss.str(); } inline void PR(void) {} inline void PR(int x) { printf("%d", x); } inline void PR(long long x) { printf("%lld", x); } inline void PR(char *s) { printf("%s", s); } inline void PR(const char *s) { printf("%s", s); } inline void PR(double f) { printf("%.10lf", f); } inline void PR(long double f) { printf("%.10llf", f); } inline void PR(vector<int> &vec) { for (auto x : vec) { PR(x); putc(0x20, stdout); } } template <typename T> inline void PRS(T x) { PR(x); putc(0x20, stdout); } template <typename T> inline void PRN(T x) { PR(x); putc(0x0a, stdout); } void PRN(void) { putc(0x0a, stdout); } inline int gcd(int a, int b) { return a ? gcd(b % a, a) : b; } inline long long gcd(long long a, long long b) { return a ? gcd(b % a, a) : b; } inline long long powmod(long long a, long long p, long long m) { long long r = 1; while (p) { if (p & 1) r = r * a % m; p >>= 1; a = a * a % m; } return r; } struct pairhash { template <typename T, typename U> std::size_t operator()(const std::pair<T, U> &x) const { return std::hash<T>()(x.first) ^ std::hash<U>()(x.second); } }; template <typename K, typename V> V GetWithDef(const std::map<K, V> &m, const K &key, const V &defval) { auto it = m.find(key); return (it == m.end()) ? defval : it->second; } template <typename K, typename V> void SetDef(std::map<K, V> &m, const K &key, const V &defval) { auto it = m.find(key); if (it == m.end()) m[key] = defval; } template <typename K, typename V> V GetWithDef(const std::unordered_map<K, V> &m, const K &key, const V &defval) { auto it = m.find(key); return (it == m.end()) ? defval : it->second; } template <typename K, typename V> void SetDef(std::unordered_map<K, V> &m, const K &key, const V &defval) { auto it = m.find(key); if (it == m.end()) m[key] = defval; } const int MOD = 1000 * 1000 * 1000 + 7; const double PI = 3.1415926535897932384626433832795l; inline void addto(int &a, int b) { a += b; if (a >= MOD) a -= MOD; } inline int add(int a, int b) { a += b; if (a >= MOD) a -= MOD; return a; } inline void subto(int &a, int b) { a -= b; if (a < 0) a += MOD; if (a >= MOD) a -= MOD; } inline int sub(int a, int b) { a -= b; if (a < 0) a += MOD; if (a >= MOD) a -= MOD; return a; } inline void multo(int &a, int b) { a = (long long)a * b % MOD; } inline int mul(int a, int b) { return (long long)a * b % MOD; } inline int mulmod(int a, int b, int mod) { return (long long)a * b % mod; } inline int powmod(int a, int e, int mod) { int x; for (x = 1; e > 0; e >>= 1) { if (e & 1) x = mulmod(x, a, mod); a = mulmod(a, a, mod); } return x; } inline int invmod_prime(int a, int mod) { return powmod(a, mod - 2, mod); } inline long long invmod_LL(long long p) { long long q = p; for (long long a = p * p; a != 1; a *= a) q *= a; return q; } const int ZERO = 1e9; struct Node; Node *allocNode(int l, int r); struct Node { int my_l, my_r; Node *pleft = NULL; Node *pright = NULL; int my_val; int my_lazy; Node() {} inline bool inside(int l, int r) { return (l <= my_l) && (my_r <= r); } inline bool outside(int l, int r) { return (r < my_l) || (l > my_r); } inline bool single() { return (my_l == my_r); } inline int length() { return (my_r - my_l + 1); } inline void check_fork() { if (pleft) return; assert(!single()); pleft = allocNode(my_l, (my_l + my_r) / 2); pright = allocNode((my_l + my_r) / 2 + 1, my_r); } inline Node *left() { check_fork(); return pleft; } inline Node *right() { check_fork(); return pright; } void clear() { if (pleft) { pleft->clear(); delete pleft; } if (pright) { pright->clear(); delete pright; } } inline static int combine(int a, int b) { return min(a, b); } int sum_range(int l, int r) { push(); if (outside(l, r)) return ZERO; if (inside(l, r)) return my_val; return combine(left()->sum_range(l, r), right()->sum_range(l, r)); } int get_single(int l) { return sum_range(l, l); } void set_single(int x, int new_val) { push(); if (outside(x, x)) return; if ((my_l == my_r) && (my_l == x)) { my_val = new_val; return; } left()->set_single(x, new_val); right()->set_single(x, new_val); my_val = combine(left()->my_val, right()->my_val); } void modify_single(int x, int new_val) { push(); if (outside(x, x)) return; if ((my_l == my_r) && (my_l == x)) { my_val = combine(my_val, new_val); return; } left()->modify_single(x, new_val); right()->modify_single(x, new_val); my_val = combine(left()->my_val, right()->my_val); } void modify_range(int l, int r, int new_val) { push(); if (outside(l, r)) return; if (inside(l, r)) { my_lazy = combine(my_lazy, new_val); return; } left()->modify_range(l, r, new_val); right()->modify_range(l, r, new_val); my_val = combine(left()->my_val, right()->my_val); } void push() { return; if (!single()) { left()->my_lazy = combine(left()->my_lazy, my_lazy); right()->my_lazy = combine(right()->my_lazy, my_lazy); } my_val = combine(my_val, my_lazy); my_lazy = ZERO; } }; struct WideNode; WideNode *allocWideNode(int l, int r, int l2, int r2); struct WideNode { int my_l, my_r; WideNode *pleft = NULL; WideNode *pright = NULL; Node *my_val = NULL; WideNode() {} inline bool inside(int l, int r) { return (l <= my_l) && (my_r <= r); } inline bool outside(int l, int r) { return (r < my_l) || (l > my_r); } inline bool single() { return (my_l == my_r); } inline int length() { return (my_r - my_l + 1); } inline void check_fork() { if (pleft) return; assert(!single()); pleft = allocWideNode(my_l, (my_l + my_r) / 2, my_val->my_l, my_val->my_r); pright = allocWideNode((my_l + my_r) / 2 + 1, my_r, my_val->my_l, my_val->my_r); } inline WideNode *left() { check_fork(); return pleft; } inline WideNode *right() { check_fork(); return pright; } void clear() { if (pleft) { pleft->clear(); delete pleft; } if (pright) { pright->clear(); delete pright; } my_val->clear(); } int sum_range(int l, int r, int l2, int r2) { if (outside(l, r)) return ZERO; if (inside(l, r)) return my_val->sum_range(l2, r2); return Node::combine(left()->sum_range(l, r, l2, r2), right()->sum_range(l, r, l2, r2)); } int get_single(int l, int l2) { return sum_range(l, l, l2, l2); } void set_single(int x, int y, int new_val) { if (outside(x, x)) return; if ((my_l == my_r) && (my_l == x)) { my_val->set_single(y, new_val); return; } left()->set_single(x, y, new_val); right()->set_single(x, y, new_val); my_val->modify_single(y, new_val); } void modify_single(int x, int y, int new_val) { if (outside(x, x)) return; if ((my_l == my_r) && (my_l == x)) { my_val->set_single(y, Node::combine(my_val->get_single(y), new_val)); return; } left()->modify_single(x, y, new_val); right()->modify_single(x, y, new_val); merge_at(y); } void merge_at(int y) { my_val->set_single(y, Node::combine(left()->my_val->get_single(y), right()->my_val->get_single(y))); } }; Node memNode[5123123]; int ptrNode = 0; Node *allocNode(int l, int r) { Node &node = memNode[ptrNode++]; assert(ptrNode < 5123123); node.my_l = l; node.my_r = r; node.my_val = ZERO; node.my_lazy = ZERO; node.pleft = NULL; node.pright = NULL; return &node; } WideNode memWideNode[123123]; int ptrWideNode = 0; WideNode *allocWideNode(int l, int r, int l2, int r2) { WideNode &node = memWideNode[ptrWideNode++]; assert(ptrWideNode < 123123); node.my_l = l; node.my_r = r; node.my_val = allocNode(l2, r2); node.pleft = NULL; node.pright = NULL; return &node; } int N, M, K, L, E, Q, P, SY, SX; int arr[301] = {}; int mp[301][301] = {}; int mp_rot[4][301][301] = {}; vector<pair<int, int>> by_val[301 * 301]; int min_dist[500][500] = {}; int cx; int cy; bool funcless(pair<int, int> yx1, pair<int, int> yx2) { int y1 = yx1.first; int x1 = yx1.second; int y2 = yx2.first; int x2 = yx2.second; return abs(cx - x1) + abs(cy - y1) < abs(cx - x2) + abs(cy - y2); } inline void rotate90cw(int &y, int &x, int sy, int sx) { int x2 = sy - 1 - y; y = x; x = x2; } template <typename T> void rotate90cw(T src[301][301], T dst[301][301], int sy, int sx) { for (__typeof(sx) x = (0), __tmpvar__end475 = (sx); x < __tmpvar__end475; x++) { for (__typeof(sy) y = (0), __tmpvar__end476 = (sy); y < __tmpvar__end476; y++) { int y2 = x; int x2 = sy - 1 - y; dst[y2][x2] = src[y][x]; } } } int main() { ios_base::sync_with_stdio(0); scanf("%d%d%d", &SY, &SX, &P); for (__typeof(SY) y = (0), __tmpvar__end491 = (SY); y < __tmpvar__end491; y++) { for (__typeof(SX) x = (0), __tmpvar__end492 = (SX); x < __tmpvar__end492; x++) { scanf("%d", &mp[y][x]); by_val[mp[y][x]].push_back(make_pair(y, x)); min_dist[y][x] = 1e9; } } rotate90cw(mp, mp_rot[0], SY, SX); rotate90cw(mp_rot[0], mp_rot[1], SX, SY); rotate90cw(mp_rot[1], mp_rot[2], SY, SX); rotate90cw(mp_rot[2], mp_rot[3], SX, SY); rotate90cw(mp_rot[3], mp_rot[0], SY, SX); int ans = 1e9; for (auto &yx : by_val[1]) { int y = yx.first; int x = yx.second; min_dist[y][x] = y + x; if (P == 1) UPDATE_MIN(ans, x + y); } for (__typeof(P) val = (1), __tmpvar__end510 = (P); val < __tmpvar__end510; val++) { 1; WideNode *nodes[4] = { allocWideNode(0, 301, 0, 301), allocWideNode(0, 301, 0, 301), allocWideNode(0, 301, 0, 301), allocWideNode(0, 301, 0, 301)}; for (auto &yx : by_val[val]) { int y = yx.first; int x = yx.second; int dist = min_dist[y][x]; int sy = SY; int sx = SX; for (__typeof(4) r = (0), __tmpvar__end521 = (4); r < __tmpvar__end521; r++) { nodes[r]->set_single(x, y, dist + x + y); rotate90cw(y, x, sy, sx); swap(sy, sx); } } for (auto &yx2 : by_val[val + 1]) { int y2 = yx2.first; int x2 = yx2.second; int sy = SY; int sx = SX; int xorig = x2; int yorig = y2; for (__typeof(4) r = (0), __tmpvar__end536 = (4); r < __tmpvar__end536; r++) { int dist2 = nodes[r]->sum_range(x2, sx, y2, sy) - x2 - y2; UPDATE_MIN(min_dist[yorig][xorig], dist2); if (val + 1 == P) UPDATE_MIN(ans, dist2); rotate90cw(y2, x2, sy, sx); swap(sy, sx); } } ptrNode = 0; ptrWideNode = 0; 1; } PRN(ans); return 0; priority_queue<pair<int, pair<int, int>>> pq; for (auto &yx : by_val[1]) { int y = yx.first; int x = yx.second; int dist = y + x; pq.push(make_pair(-dist, yx)); min_dist[y][x] = dist; 1; } while (!pq.empty()) { auto s = pq.top(); pq.pop(); int dist = -s.first; if (dist >= ans) break; int y = s.second.first; int x = s.second.second; if (dist != min_dist[y][x]) continue; int val = mp[y][x]; for (auto &yx2 : by_val[val + 1]) { int y2 = yx2.first; int x2 = yx2.second; int dist2 = dist + abs(y2 - y) + abs(x2 - x); int val2 = mp[y2][x2]; 1; if (val2 == P) UPDATE_MIN(ans, dist2); else if (dist2 < ans && dist2 < min_dist[y2][x2]) { min_dist[y2][x2] = dist2; pq.push(make_pair(-dist2, yx2)); } } } PRN(ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; struct data { int x, y, val, minVal, rMin; data(int X, int Y) { x = X; y = Y; val = 0; minVal = 1e9; rMin = 1e9; } }; vector<data> a[int(1e5 + 100)]; int Small, n, m, p; bool cmp(data x, data y) { return x.val < y.val; } bool cmp2(data x, data y) { return x.x < y.x; } int dist(data x, data y) { return abs(x.x - y.x) + abs(x.y - y.y); } int Find(int x, int l, int val) { int Left = 0; int Right = a[x].size() - 1 - l; int ans = 0; while (Left <= Right) { int mid = (Left + Right) >> 1; if (a[x][mid].x > val) Right = mid - 1; else { Left = mid + 1; ans = mid; } } return ans; } int fInd(int x, int l, int val) { int Left = 0; int Right = a[x].size() - 1; int ans = a[x].size() - 1 - l; while (Left <= Right) { int mid = (Left + Right) >> 1; if (a[x][mid].x < val) Left = mid + 1; else { Right = mid - 1; ans = mid; } } return ans; } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); a[x].push_back(data(i, j)); } Small = 1e9; for (int i = 0; i < a[1].size(); i++) { a[1][i].val = a[1][i].x + a[1][i].y - 2; a[1][i].rMin = a[1][i].val; a[1][i].minVal = a[1][i].val; Small = min(Small, a[1][i].val); } sort(a[1].begin(), a[1].end(), cmp); for (int i = 1; i < a[1].size(); i++) a[1][i].minVal = min(a[1][i - 1].minVal, a[1][i].val); for (int i = int(a[1].size()) - 2; i >= 0; i--) a[1][i].rMin = min(a[1][i + 1].rMin, a[1][i].val); int l = max(0, int(a[1].size()) - n - m); int x = a[1].size() - 1; while (a[1][x].val - Small > n + m) { l++; x--; } sort(a[1].begin(), a[1].begin() + int(a[1].size()) - l, cmp2); for (int i = 2; i <= p; i++) { for (int j = 0; j < a[i].size(); j++) { int x = Find(i - 1, l, a[i][j].x); int y = fInd(i - 1, l, a[i][j].x); int tmp = dist(a[i - 1][x], a[i][j]) + a[i - 1][x].val; tmp = min(tmp, dist(a[i - 1][y], a[i][j]) + a[i - 1][y].val); Small = 1e9; while (x > 0 || y < int(a[i - 1].size()) - 1 - l) { if (x > 0) { if (abs(a[i - 1][x - 1].x - a[i][j].x) >= tmp) x = 0; else { x--; tmp = min(tmp, dist(a[i - 1][x], a[i][j]) + a[i - 1][x].val); } } if (y < int(a[i - 1].size()) - 1 - l) { if (abs(a[i - 1][y + 1].x - a[i][j].x) >= tmp) y = a[i - 1].size() - 1 - l; else { y++; tmp = min(tmp, dist(a[i - 1][y], a[i][j]) + a[i - 1][y].val); } } } if (tmp - Small > n + m) continue; a[i][j].val = tmp; a[i][j].minVal = tmp; a[i][j].rMin = tmp; Small = min(Small, tmp); } l = max(0, int(a[i].size()) - n - m); sort(a[i].begin(), a[i].end(), cmp); a[i][0].minVal = a[i][0].val; a[i][a[i].size() - 1].rMin = a[i][a[i].size() - 1].val; int x = a[i].size() - l - 1; while (a[i][x].val - Small > n + m) { l++; x--; } sort(a[i].begin(), a[i].begin() + int(a[i].size()) - l, cmp2); for (int j = 1; j < a[i].size() - l; j++) a[i][j].minVal = min(a[i][j - 1].minVal, a[i][j].minVal); for (int j = int(a[i].size()) - 2 - l; j >= 0; j--) a[i][j].rMin = min(a[i][j + 1].rMin, a[i][j].rMin); } int ans = Small; cout << ans; }
### Prompt Create a solution in CPP for the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct data { int x, y, val, minVal, rMin; data(int X, int Y) { x = X; y = Y; val = 0; minVal = 1e9; rMin = 1e9; } }; vector<data> a[int(1e5 + 100)]; int Small, n, m, p; bool cmp(data x, data y) { return x.val < y.val; } bool cmp2(data x, data y) { return x.x < y.x; } int dist(data x, data y) { return abs(x.x - y.x) + abs(x.y - y.y); } int Find(int x, int l, int val) { int Left = 0; int Right = a[x].size() - 1 - l; int ans = 0; while (Left <= Right) { int mid = (Left + Right) >> 1; if (a[x][mid].x > val) Right = mid - 1; else { Left = mid + 1; ans = mid; } } return ans; } int fInd(int x, int l, int val) { int Left = 0; int Right = a[x].size() - 1; int ans = a[x].size() - 1 - l; while (Left <= Right) { int mid = (Left + Right) >> 1; if (a[x][mid].x < val) Left = mid + 1; else { Right = mid - 1; ans = mid; } } return ans; } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); a[x].push_back(data(i, j)); } Small = 1e9; for (int i = 0; i < a[1].size(); i++) { a[1][i].val = a[1][i].x + a[1][i].y - 2; a[1][i].rMin = a[1][i].val; a[1][i].minVal = a[1][i].val; Small = min(Small, a[1][i].val); } sort(a[1].begin(), a[1].end(), cmp); for (int i = 1; i < a[1].size(); i++) a[1][i].minVal = min(a[1][i - 1].minVal, a[1][i].val); for (int i = int(a[1].size()) - 2; i >= 0; i--) a[1][i].rMin = min(a[1][i + 1].rMin, a[1][i].val); int l = max(0, int(a[1].size()) - n - m); int x = a[1].size() - 1; while (a[1][x].val - Small > n + m) { l++; x--; } sort(a[1].begin(), a[1].begin() + int(a[1].size()) - l, cmp2); for (int i = 2; i <= p; i++) { for (int j = 0; j < a[i].size(); j++) { int x = Find(i - 1, l, a[i][j].x); int y = fInd(i - 1, l, a[i][j].x); int tmp = dist(a[i - 1][x], a[i][j]) + a[i - 1][x].val; tmp = min(tmp, dist(a[i - 1][y], a[i][j]) + a[i - 1][y].val); Small = 1e9; while (x > 0 || y < int(a[i - 1].size()) - 1 - l) { if (x > 0) { if (abs(a[i - 1][x - 1].x - a[i][j].x) >= tmp) x = 0; else { x--; tmp = min(tmp, dist(a[i - 1][x], a[i][j]) + a[i - 1][x].val); } } if (y < int(a[i - 1].size()) - 1 - l) { if (abs(a[i - 1][y + 1].x - a[i][j].x) >= tmp) y = a[i - 1].size() - 1 - l; else { y++; tmp = min(tmp, dist(a[i - 1][y], a[i][j]) + a[i - 1][y].val); } } } if (tmp - Small > n + m) continue; a[i][j].val = tmp; a[i][j].minVal = tmp; a[i][j].rMin = tmp; Small = min(Small, tmp); } l = max(0, int(a[i].size()) - n - m); sort(a[i].begin(), a[i].end(), cmp); a[i][0].minVal = a[i][0].val; a[i][a[i].size() - 1].rMin = a[i][a[i].size() - 1].val; int x = a[i].size() - l - 1; while (a[i][x].val - Small > n + m) { l++; x--; } sort(a[i].begin(), a[i].begin() + int(a[i].size()) - l, cmp2); for (int j = 1; j < a[i].size() - l; j++) a[i][j].minVal = min(a[i][j - 1].minVal, a[i][j].minVal); for (int j = int(a[i].size()) - 2 - l; j >= 0; j--) a[i][j].rMin = min(a[i][j + 1].rMin, a[i][j].rMin); } int ans = Small; cout << ans; } ```
#include <bits/stdc++.h> using namespace std; struct point { int x, y; int64_t time; int dist(const point& p) const { return abs(x - p.x) + abs(y - p.y); } bool operator<(const point& p) const { return time > p.time; } }; int n, m, p; vector<point> s[300 * 300 + 1]; int64_t t[300][300]; int main() { cin >> n >> m >> p; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { int x; cin >> x; s[x].push_back({i, j, i + j}); } for (int i = 2; i <= p; ++i) { if (s[i - 1].size() * s[i].size() < size_t(m * n) * 256) { for (point& to : s[i]) { to.time = int64_t(1) << 60; for (point from : s[i - 1]) to.time = min(to.time, from.time + from.dist(to)); } } else { for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) t[i][j] = -1; priority_queue<point> q; auto put = [&](point p) { if (0 <= p.x && p.x < n && 0 <= p.y && p.y < m && t[p.x][p.y] == -1) { t[p.x][p.y] = p.time; q.push(p); } }; for (point from : s[i - 1]) q.push(from); while (!q.empty()) { point p = q.top(); q.pop(); if (t[p.x][p.y] == -1) t[p.x][p.y] = p.time; put({p.x - 1, p.y, p.time + 1}); put({p.x + 1, p.y, p.time + 1}); put({p.x, p.y - 1, p.time + 1}); put({p.x, p.y + 1, p.time + 1}); } for (point& to : s[i]) to.time = t[to.x][to.y]; } } cout << s[p][0].time << endl; return 0; }
### Prompt In cpp, your task is to solve the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct point { int x, y; int64_t time; int dist(const point& p) const { return abs(x - p.x) + abs(y - p.y); } bool operator<(const point& p) const { return time > p.time; } }; int n, m, p; vector<point> s[300 * 300 + 1]; int64_t t[300][300]; int main() { cin >> n >> m >> p; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { int x; cin >> x; s[x].push_back({i, j, i + j}); } for (int i = 2; i <= p; ++i) { if (s[i - 1].size() * s[i].size() < size_t(m * n) * 256) { for (point& to : s[i]) { to.time = int64_t(1) << 60; for (point from : s[i - 1]) to.time = min(to.time, from.time + from.dist(to)); } } else { for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) t[i][j] = -1; priority_queue<point> q; auto put = [&](point p) { if (0 <= p.x && p.x < n && 0 <= p.y && p.y < m && t[p.x][p.y] == -1) { t[p.x][p.y] = p.time; q.push(p); } }; for (point from : s[i - 1]) q.push(from); while (!q.empty()) { point p = q.top(); q.pop(); if (t[p.x][p.y] == -1) t[p.x][p.y] = p.time; put({p.x - 1, p.y, p.time + 1}); put({p.x + 1, p.y, p.time + 1}); put({p.x, p.y - 1, p.time + 1}); put({p.x, p.y + 1, p.time + 1}); } for (point& to : s[i]) to.time = t[to.x][to.y]; } } cout << s[p][0].time << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MOD(1000000007); const int INF((1 << 30) - 1); const int MAXN(305); struct cell { int x, y, v; cell(){}; cell(int x, int y, int v) : x(x), y(y), v(v){}; bool operator<(const cell &other) const { return v < other.v; } }; vector<cell> a[MAXN * MAXN]; int cnt[MAXN * MAXN], d[MAXN][MAXN], dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; int main() { int n, m, p; scanf("%d%d%d", &n, &m, &p); int r = sqrt(n * m), ans = INF; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; scanf("%d", &x); cnt[x]++; if (x == 1) { a[x].push_back(cell(i, j, i + j)); ans = min(ans, i + j); } else { a[x].push_back(cell(i, j, INF)); } } for (int i = 2; i <= p; i++) { if (cnt[i - 1] <= r) { for (int j = 0; j < a[i].size(); j++) { int x1 = a[i][j].x; int y1 = a[i][j].y; for (int k = 0; k < a[i - 1].size(); k++) { int x2 = a[i - 1][k].x; int y2 = a[i - 1][k].y; a[i][j].v = min(a[i][j].v, a[i - 1][k].v + abs(x1 - x2) + abs(y1 - y2)); } } } else { sort(a[i - 1].begin(), a[i - 1].end()); queue<pair<int, int> > q; for (int j = 0; j < n; j++) for (int k = 0; k < m; k++) d[j][k] = INF; int now = 0; while (now < a[i - 1].size() && a[i - 1][now].v == a[i - 1][0].v) { int x = a[i - 1][now].x; int y = a[i - 1][now].y; q.push(pair<int, int>(x, y)); d[x][y] = a[i - 1][now].v; now++; } while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for (int k = 0; k < 4; k++) { int tx = x + dir[k][0]; int ty = y + dir[k][1]; if (tx < 0 || tx >= n || ty < 0 || ty >= m) continue; if (d[tx][ty] != INF) continue; q.push(pair<int, int>(tx, ty)); d[tx][ty] = d[x][y] + 1; while (now < a[i - 1].size() && a[i - 1][now].v == d[x][y] + 1) { tx = a[i - 1][now].x; ty = a[i - 1][now].y; q.push(pair<int, int>(tx, ty)); d[tx][ty] = d[x][y] + 1; now++; } } } for (int j = 0; j < a[i].size(); j++) a[i][j].v = d[a[i][j].x][a[i][j].y]; } } printf("%d", a[p][0].v); }
### Prompt Please provide a cpp coded solution to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MOD(1000000007); const int INF((1 << 30) - 1); const int MAXN(305); struct cell { int x, y, v; cell(){}; cell(int x, int y, int v) : x(x), y(y), v(v){}; bool operator<(const cell &other) const { return v < other.v; } }; vector<cell> a[MAXN * MAXN]; int cnt[MAXN * MAXN], d[MAXN][MAXN], dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; int main() { int n, m, p; scanf("%d%d%d", &n, &m, &p); int r = sqrt(n * m), ans = INF; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; scanf("%d", &x); cnt[x]++; if (x == 1) { a[x].push_back(cell(i, j, i + j)); ans = min(ans, i + j); } else { a[x].push_back(cell(i, j, INF)); } } for (int i = 2; i <= p; i++) { if (cnt[i - 1] <= r) { for (int j = 0; j < a[i].size(); j++) { int x1 = a[i][j].x; int y1 = a[i][j].y; for (int k = 0; k < a[i - 1].size(); k++) { int x2 = a[i - 1][k].x; int y2 = a[i - 1][k].y; a[i][j].v = min(a[i][j].v, a[i - 1][k].v + abs(x1 - x2) + abs(y1 - y2)); } } } else { sort(a[i - 1].begin(), a[i - 1].end()); queue<pair<int, int> > q; for (int j = 0; j < n; j++) for (int k = 0; k < m; k++) d[j][k] = INF; int now = 0; while (now < a[i - 1].size() && a[i - 1][now].v == a[i - 1][0].v) { int x = a[i - 1][now].x; int y = a[i - 1][now].y; q.push(pair<int, int>(x, y)); d[x][y] = a[i - 1][now].v; now++; } while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for (int k = 0; k < 4; k++) { int tx = x + dir[k][0]; int ty = y + dir[k][1]; if (tx < 0 || tx >= n || ty < 0 || ty >= m) continue; if (d[tx][ty] != INF) continue; q.push(pair<int, int>(tx, ty)); d[tx][ty] = d[x][y] + 1; while (now < a[i - 1].size() && a[i - 1][now].v == d[x][y] + 1) { tx = a[i - 1][now].x; ty = a[i - 1][now].y; q.push(pair<int, int>(tx, ty)); d[tx][ty] = d[x][y] + 1; now++; } } } for (int j = 0; j < a[i].size(); j++) a[i][j].v = d[a[i][j].x][a[i][j].y]; } } printf("%d", a[p][0].v); } ```
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int N = 3e2 + 5; queue<pair<int, int> > q; vector<pair<int, int> > v[N * N]; int n, m, p; int a[N][N], f[N][N]; int *ans; int dis(int x, int y, int a, int b) { return abs(x - a) + abs(y - b); } void init() { for (int i = 0; i <= n * m; i++) v[i].clear(); memset(f, inf, sizeof(f)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]), v[a[i][j]].push_back(pair<int, int>(i, j)); if (a[i][j] == 1) f[i][j] = abs(1 - i) + abs(1 - j); if (a[i][j] == p) ans = &f[i][j]; } } } int dx[] = {-1, 1, 0, 0}, w[N][N]; int dy[] = {0, 0, -1, 1}; void bfs(int dep) { memset(w, inf, sizeof(w)); for (int i = 0; i < v[dep].size(); i++) { int x = v[dep][i].first, y = v[dep][i].second; q.push(v[dep][i]); w[x][y] = f[x][y]; } while (!q.empty()) { pair<int, int> t = q.front(); q.pop(); int x = t.first, y = t.second, dis = w[x][y]; for (int i = 0; i < 4; i++) { int c = x + dx[i], d = y + dy[i]; if (c >= 1 && c <= n && d >= 1 && d <= m) { if (w[c][d] > dis + 1) { w[c][d] = dis + 1; if (a[c][d] == dep + 1) f[c][d] = dis + 1; q.push(pair<int, int>(c, d)); } } } } } void solve() { int i, j, x, c, y, d; for (int k = 2; k <= p; k++) { if (v[k - 1].size() * v[k].size() < n * m) { for (i = 0; i < v[k - 1].size(); i++) { for (j = 0; j < v[k].size(); j++) { x = v[k][j].first, y = v[k][j].second; c = v[k - 1][i].first, d = v[k - 1][i].second; f[x][y] = min(f[x][y], f[c][d] + dis(x, y, c, d)); } } } else bfs(k - 1); } printf("%d\n", *ans); } int main() { cin >> n >> m >> p; init(); solve(); return 0; }
### Prompt Develop a solution in Cpp to the problem described below: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int N = 3e2 + 5; queue<pair<int, int> > q; vector<pair<int, int> > v[N * N]; int n, m, p; int a[N][N], f[N][N]; int *ans; int dis(int x, int y, int a, int b) { return abs(x - a) + abs(y - b); } void init() { for (int i = 0; i <= n * m; i++) v[i].clear(); memset(f, inf, sizeof(f)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]), v[a[i][j]].push_back(pair<int, int>(i, j)); if (a[i][j] == 1) f[i][j] = abs(1 - i) + abs(1 - j); if (a[i][j] == p) ans = &f[i][j]; } } } int dx[] = {-1, 1, 0, 0}, w[N][N]; int dy[] = {0, 0, -1, 1}; void bfs(int dep) { memset(w, inf, sizeof(w)); for (int i = 0; i < v[dep].size(); i++) { int x = v[dep][i].first, y = v[dep][i].second; q.push(v[dep][i]); w[x][y] = f[x][y]; } while (!q.empty()) { pair<int, int> t = q.front(); q.pop(); int x = t.first, y = t.second, dis = w[x][y]; for (int i = 0; i < 4; i++) { int c = x + dx[i], d = y + dy[i]; if (c >= 1 && c <= n && d >= 1 && d <= m) { if (w[c][d] > dis + 1) { w[c][d] = dis + 1; if (a[c][d] == dep + 1) f[c][d] = dis + 1; q.push(pair<int, int>(c, d)); } } } } } void solve() { int i, j, x, c, y, d; for (int k = 2; k <= p; k++) { if (v[k - 1].size() * v[k].size() < n * m) { for (i = 0; i < v[k - 1].size(); i++) { for (j = 0; j < v[k].size(); j++) { x = v[k][j].first, y = v[k][j].second; c = v[k - 1][i].first, d = v[k - 1][i].second; f[x][y] = min(f[x][y], f[c][d] + dis(x, y, c, d)); } } } else bfs(k - 1); } printf("%d\n", *ans); } int main() { cin >> n >> m >> p; init(); solve(); return 0; } ```
#include <bits/stdc++.h> using namespace std; struct data { int x, y, val; data(int X, int Y) { x = X; y = Y; val = 1e9; } }; vector<data> a[int(1e5 + 100)]; int Small, n, m, p; bool cmp(data x, data y) { return x.val < y.val; } bool cmp2(data x, data y) { return x.x < y.x; } int dist(data x, data y) { return abs(x.x - y.x) + abs(x.y - y.y); } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); a[x].push_back(data(i, j)); } Small = 1e9; for (int i = 0; i < a[1].size(); i++) { a[1][i].val = a[1][i].x + a[1][i].y - 2; Small = min(Small, a[1][i].val); } int l = max(0, int(a[1].size()) - n - m); int x = a[1].size() - l - 1; sort(a[1].begin(), a[1].end(), cmp); while (a[1][x].val - Small > n + m) { l++; x--; } sort(a[1].begin(), a[1].begin() + int(a[1].size()) - l, cmp2); for (int i = 2; i <= p; i++) { Small = 1e9; for (int j = 0; j < a[i].size(); j++) { int tmp = 1e9; for (int k = 0; k < a[i - 1].size() - l; k++) tmp = min(tmp, dist(a[i][j], a[i - 1][k]) + a[i - 1][k].val); Small = min(Small, tmp); a[i][j].val = tmp; } l = max(0, int(a[i].size()) - n - m); sort(a[i].begin(), a[i].end(), cmp); int x = a[i].size() - l - 1; while (a[i][x].val - Small > n + m) { l++; x--; } sort(a[i].begin(), a[i].begin() + int(a[i].size()) - l, cmp2); } int ans = Small; cout << ans; }
### Prompt In CPP, your task is to solve the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct data { int x, y, val; data(int X, int Y) { x = X; y = Y; val = 1e9; } }; vector<data> a[int(1e5 + 100)]; int Small, n, m, p; bool cmp(data x, data y) { return x.val < y.val; } bool cmp2(data x, data y) { return x.x < y.x; } int dist(data x, data y) { return abs(x.x - y.x) + abs(x.y - y.y); } int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); a[x].push_back(data(i, j)); } Small = 1e9; for (int i = 0; i < a[1].size(); i++) { a[1][i].val = a[1][i].x + a[1][i].y - 2; Small = min(Small, a[1][i].val); } int l = max(0, int(a[1].size()) - n - m); int x = a[1].size() - l - 1; sort(a[1].begin(), a[1].end(), cmp); while (a[1][x].val - Small > n + m) { l++; x--; } sort(a[1].begin(), a[1].begin() + int(a[1].size()) - l, cmp2); for (int i = 2; i <= p; i++) { Small = 1e9; for (int j = 0; j < a[i].size(); j++) { int tmp = 1e9; for (int k = 0; k < a[i - 1].size() - l; k++) tmp = min(tmp, dist(a[i][j], a[i - 1][k]) + a[i - 1][k].val); Small = min(Small, tmp); a[i][j].val = tmp; } l = max(0, int(a[i].size()) - n - m); sort(a[i].begin(), a[i].end(), cmp); int x = a[i].size() - l - 1; while (a[i][x].val - Small > n + m) { l++; x--; } sort(a[i].begin(), a[i].begin() + int(a[i].size()) - l, cmp2); } int ans = Small; cout << ans; } ```
#include <bits/stdc++.h> using namespace std; int INF = 310 * 310 * 310; int n, m, p; int dp[310][310]; int a[310][310]; vector<pair<int, int> > s[310 * 310]; int d_x[] = {0, 0, 1, -1}; int d_y[] = {1, -1, 0, 0}; void bfs(int node) { queue<pair<int, int> > q; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] != node) dp[i][j] = INF; else q.push({i, j}); while (!q.empty()) { int row = q.front().first, col = q.front().second; int dist = dp[row][col]; q.pop(); for (int i = 0; i < 4; i++) { int new_row = row + d_x[i], new_col = col + d_y[i]; if (new_row < 0 || new_row >= n || new_col < 0 || new_col >= n || dp[new_row][new_col] <= dist + 1) continue; dp[new_row][new_col] = dist + 1; q.push({new_row, new_col}); } } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] != node + 1) dp[i][j] = INF; } int solve_dp() { for (int i = 0; i < s[1].size(); i++) { int row = s[1][i].first, col = s[1][i].second; dp[row][col] = row + col; } for (int i = 2; i <= p; i++) { if (s[i].size() * s[i - 1].size() < 300 * 300 * 10) for (int j = 0; j < s[i].size(); j++) { for (int k = 0; k < s[i - 1].size(); k++) { int row = s[i][j].first, col = s[i][j].second; int other_row = s[i - 1][k].first, other_col = s[i - 1][k].second; int other_dp = dp[other_row][other_col]; int dist = abs(row - other_row) + abs(col - other_col); dp[row][col] = min(dp[row][col], other_dp + dist); } } else bfs(i - 1); } int ans = INF; for (int i = 0; i < s[p].size(); i++) { ans = min(ans, dp[s[p][i].first][s[p][i].second]); } return ans; } int main() { scanf("%d %d %d", &n, &m, &p); memset(dp, INF, sizeof dp); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &a[i][j]); s[a[i][j]].push_back(make_pair(i, j)); } } printf("%d\n", solve_dp()); return 0; }
### Prompt In cpp, your task is to solve the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int INF = 310 * 310 * 310; int n, m, p; int dp[310][310]; int a[310][310]; vector<pair<int, int> > s[310 * 310]; int d_x[] = {0, 0, 1, -1}; int d_y[] = {1, -1, 0, 0}; void bfs(int node) { queue<pair<int, int> > q; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] != node) dp[i][j] = INF; else q.push({i, j}); while (!q.empty()) { int row = q.front().first, col = q.front().second; int dist = dp[row][col]; q.pop(); for (int i = 0; i < 4; i++) { int new_row = row + d_x[i], new_col = col + d_y[i]; if (new_row < 0 || new_row >= n || new_col < 0 || new_col >= n || dp[new_row][new_col] <= dist + 1) continue; dp[new_row][new_col] = dist + 1; q.push({new_row, new_col}); } } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] != node + 1) dp[i][j] = INF; } int solve_dp() { for (int i = 0; i < s[1].size(); i++) { int row = s[1][i].first, col = s[1][i].second; dp[row][col] = row + col; } for (int i = 2; i <= p; i++) { if (s[i].size() * s[i - 1].size() < 300 * 300 * 10) for (int j = 0; j < s[i].size(); j++) { for (int k = 0; k < s[i - 1].size(); k++) { int row = s[i][j].first, col = s[i][j].second; int other_row = s[i - 1][k].first, other_col = s[i - 1][k].second; int other_dp = dp[other_row][other_col]; int dist = abs(row - other_row) + abs(col - other_col); dp[row][col] = min(dp[row][col], other_dp + dist); } } else bfs(i - 1); } int ans = INF; for (int i = 0; i < s[p].size(); i++) { ans = min(ans, dp[s[p][i].first][s[p][i].second]); } return ans; } int main() { scanf("%d %d %d", &n, &m, &p); memset(dp, INF, sizeof dp); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &a[i][j]); s[a[i][j]].push_back(make_pair(i, j)); } } printf("%d\n", solve_dp()); return 0; } ```
#include <bits/stdc++.h> using namespace std; constexpr int INF = 87654321; class Fenwick { public: vector<int> tree; int length; int Rmq(int i) { int ret = INF; while (i) { ret = min(ret, tree[i]); i -= i & -i; } return ret; } void Update(int i, int val) { while (i <= length) { tree[i] = min(tree[i], val); i += i & -i; } } Fenwick() {} Fenwick(int length) : tree(length + 1, INF), length(length) {} void reset() { for (int i = 0; i < length + 1; ++i) tree[i] = INF; } }; int n, m, p; Fenwick fenwick[4]; vector<vector<int>> board, dp; vector<vector<pair<int, int>>> idx; vector<vector<pair<int, int>>> level[4], true_idx[4]; void Solve() { for (int x = 0; x < 4; ++x) { fenwick[x] = Fenwick(m); level[x].clear(); level[x].resize(p + 1); true_idx[x].clear(); true_idx[x].resize(p + 1); vector<pair<int, pair<pair<int, int>, pair<int, int>>>> chest; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { chest.push_back({board[i][j], {{i, j}, idx[i][j]}}); } } sort(chest.begin(), chest.end()); for (int i = 0; i < n * m; ++i) { level[x][chest[i].first].push_back(chest[i].second.first); true_idx[x][chest[i].first].push_back(chest[i].second.second); } vector<vector<int>> rotated_board(m + 1, vector<int>(n + 1, 0)); vector<vector<pair<int, int>>> rotated_idx( m + 1, vector<pair<int, int>>(n + 1, {0, 0})); for (int j = 1; j <= m; ++j) { for (int i = 1; i <= n; ++i) { rotated_board[j][i] = board[n + 1 - i][j]; rotated_idx[j][i] = idx[n + 1 - i][j]; } } board = rotated_board; idx = rotated_idx; swap(n, m); } dp = vector<vector<int>>(n + 1, vector<int>(m + 1, INF)); dp[level[0][p][0].first][level[0][p][0].second] = 0; for (int v = p - 1; v >= 1; --v) { for (int x = 0; x < 4; ++x) { auto& cur_tree = fenwick[x]; cur_tree.reset(); const auto& query = level[x][v]; const auto& data = level[x][v + 1]; const auto& query_idx = true_idx[x][v]; const auto& data_idx = true_idx[x][v + 1]; int i = 0, j = 0; while (i < query.size()) { while (j < data.size() && (data[j].first < query[i].first || (data[j].first == query[i].first && data[j].second < query[i].second))) { cur_tree.Update(data[j].second, dp[data_idx[j].first][data_idx[j].second] - data[j].first - data[j].second); ++j; } auto& val = dp[query_idx[i].first][query_idx[i].second]; val = min(val, cur_tree.Rmq(query[i].second) + query[i].first + query[i].second); ++i; } } } } int main() { scanf("%d%d%d", &n, &m, &p); board = vector<vector<int>>(n + 1, vector<int>(m + 1, 0)); idx = vector<vector<pair<int, int>>>(n + 1, vector<pair<int, int>>(m + 1, {0, 0})); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &board[i][j]); idx[i][j] = {i, j}; } } Solve(); int ans = INF; for (int i = 0; i < level[0][1].size(); ++i) { ans = min(ans, dp[level[0][1][i].first][level[0][1][i].second] + abs(level[0][1][i].first - 1) + abs(level[0][1][i].second - 1)); } printf("%d\n", ans); return 0; }
### Prompt Please create a solution in Cpp to the following problem: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; constexpr int INF = 87654321; class Fenwick { public: vector<int> tree; int length; int Rmq(int i) { int ret = INF; while (i) { ret = min(ret, tree[i]); i -= i & -i; } return ret; } void Update(int i, int val) { while (i <= length) { tree[i] = min(tree[i], val); i += i & -i; } } Fenwick() {} Fenwick(int length) : tree(length + 1, INF), length(length) {} void reset() { for (int i = 0; i < length + 1; ++i) tree[i] = INF; } }; int n, m, p; Fenwick fenwick[4]; vector<vector<int>> board, dp; vector<vector<pair<int, int>>> idx; vector<vector<pair<int, int>>> level[4], true_idx[4]; void Solve() { for (int x = 0; x < 4; ++x) { fenwick[x] = Fenwick(m); level[x].clear(); level[x].resize(p + 1); true_idx[x].clear(); true_idx[x].resize(p + 1); vector<pair<int, pair<pair<int, int>, pair<int, int>>>> chest; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { chest.push_back({board[i][j], {{i, j}, idx[i][j]}}); } } sort(chest.begin(), chest.end()); for (int i = 0; i < n * m; ++i) { level[x][chest[i].first].push_back(chest[i].second.first); true_idx[x][chest[i].first].push_back(chest[i].second.second); } vector<vector<int>> rotated_board(m + 1, vector<int>(n + 1, 0)); vector<vector<pair<int, int>>> rotated_idx( m + 1, vector<pair<int, int>>(n + 1, {0, 0})); for (int j = 1; j <= m; ++j) { for (int i = 1; i <= n; ++i) { rotated_board[j][i] = board[n + 1 - i][j]; rotated_idx[j][i] = idx[n + 1 - i][j]; } } board = rotated_board; idx = rotated_idx; swap(n, m); } dp = vector<vector<int>>(n + 1, vector<int>(m + 1, INF)); dp[level[0][p][0].first][level[0][p][0].second] = 0; for (int v = p - 1; v >= 1; --v) { for (int x = 0; x < 4; ++x) { auto& cur_tree = fenwick[x]; cur_tree.reset(); const auto& query = level[x][v]; const auto& data = level[x][v + 1]; const auto& query_idx = true_idx[x][v]; const auto& data_idx = true_idx[x][v + 1]; int i = 0, j = 0; while (i < query.size()) { while (j < data.size() && (data[j].first < query[i].first || (data[j].first == query[i].first && data[j].second < query[i].second))) { cur_tree.Update(data[j].second, dp[data_idx[j].first][data_idx[j].second] - data[j].first - data[j].second); ++j; } auto& val = dp[query_idx[i].first][query_idx[i].second]; val = min(val, cur_tree.Rmq(query[i].second) + query[i].first + query[i].second); ++i; } } } } int main() { scanf("%d%d%d", &n, &m, &p); board = vector<vector<int>>(n + 1, vector<int>(m + 1, 0)); idx = vector<vector<pair<int, int>>>(n + 1, vector<pair<int, int>>(m + 1, {0, 0})); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &board[i][j]); idx[i][j] = {i, j}; } } Solve(); int ans = INF; for (int i = 0; i < level[0][1].size(); ++i) { ans = min(ans, dp[level[0][1][i].first][level[0][1][i].second] + abs(level[0][1][i].first - 1) + abs(level[0][1][i].second - 1)); } printf("%d\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MaxN = 1e5 + 10; const int MOD = 1e9 + 7; const int INF = 1e9; const int K = 777; int n, m, p; int a[321][321]; int dp[321][321]; int ndp[321][321]; vector<pair<int, int> > wh[MaxN], q[MaxN]; int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &a[i][j]); wh[a[i][j]].push_back(make_pair(i, j)); } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { dp[i][j] = INF; } } dp[wh[p].back().first][wh[p].back().second] = 0; for (int it = p; it > 1; --it) { if (wh[it - 1].size() > K) { int mval = INF; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { mval = min(mval, dp[i][j]); ndp[i][j] = INF; } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (dp[i][j] < INF) { dp[i][j] -= mval; q[dp[i][j]].push_back(make_pair(i, j)); } } } for (int i = 0; i <= n + m + 5; ++i) { for (int j = 0; j < (int)q[i].size(); ++j) { int x = q[i][j].first, y = q[i][j].second; for (int dx = -1; dx <= +1; ++dx) { for (int dy = -1; dy <= +1; ++dy) { if (abs(dx) + abs(dy) != 1 || x + dx < 1 || x + dx > n || y + dy < 1 || y + dy > m) { continue; } int nx = x + dx, ny = y + dy; if (dp[nx][ny] > dp[x][y] + 1) { dp[nx][ny] = dp[x][y] + 1; q[dp[nx][ny]].push_back(make_pair(nx, ny)); } } } } q[i].clear(); } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { dp[i][j] += mval; } } vector<pair<int, int> > &v = wh[it - 1]; for (int i = 0; i < (int)v.size(); ++i) { int x = v[i].first, y = v[i].second; ndp[x][y] = dp[x][y]; } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { dp[i][j] = ndp[i][j]; } } } else { vector<pair<int, int> > &v = wh[it]; vector<pair<int, int> > &u = wh[it - 1]; for (int i = 0; i < (int)v.size(); ++i) { int x = v[i].first, y = v[i].second; if (dp[x][y] < INF) { for (int j = 0; j < (int)u.size(); ++j) { int nx = u[j].first, ny = u[j].second; int val = dp[x][y] + abs(x - nx) + abs(y - ny); if (dp[nx][ny] > val) { dp[nx][ny] = val; } } dp[x][y] = INF; } } } } int ans = INF; for (int i = 0; i < (int)wh[1].size(); ++i) { ans = min(ans, dp[wh[1][i].first][wh[1][i].second] + abs(1 - wh[1][i].first) + abs(1 - wh[1][i].second)); } printf("%d\n", ans); return 0; }
### Prompt Construct a CPP code solution to the problem outlined: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MaxN = 1e5 + 10; const int MOD = 1e9 + 7; const int INF = 1e9; const int K = 777; int n, m, p; int a[321][321]; int dp[321][321]; int ndp[321][321]; vector<pair<int, int> > wh[MaxN], q[MaxN]; int main() { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &a[i][j]); wh[a[i][j]].push_back(make_pair(i, j)); } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { dp[i][j] = INF; } } dp[wh[p].back().first][wh[p].back().second] = 0; for (int it = p; it > 1; --it) { if (wh[it - 1].size() > K) { int mval = INF; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { mval = min(mval, dp[i][j]); ndp[i][j] = INF; } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (dp[i][j] < INF) { dp[i][j] -= mval; q[dp[i][j]].push_back(make_pair(i, j)); } } } for (int i = 0; i <= n + m + 5; ++i) { for (int j = 0; j < (int)q[i].size(); ++j) { int x = q[i][j].first, y = q[i][j].second; for (int dx = -1; dx <= +1; ++dx) { for (int dy = -1; dy <= +1; ++dy) { if (abs(dx) + abs(dy) != 1 || x + dx < 1 || x + dx > n || y + dy < 1 || y + dy > m) { continue; } int nx = x + dx, ny = y + dy; if (dp[nx][ny] > dp[x][y] + 1) { dp[nx][ny] = dp[x][y] + 1; q[dp[nx][ny]].push_back(make_pair(nx, ny)); } } } } q[i].clear(); } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { dp[i][j] += mval; } } vector<pair<int, int> > &v = wh[it - 1]; for (int i = 0; i < (int)v.size(); ++i) { int x = v[i].first, y = v[i].second; ndp[x][y] = dp[x][y]; } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { dp[i][j] = ndp[i][j]; } } } else { vector<pair<int, int> > &v = wh[it]; vector<pair<int, int> > &u = wh[it - 1]; for (int i = 0; i < (int)v.size(); ++i) { int x = v[i].first, y = v[i].second; if (dp[x][y] < INF) { for (int j = 0; j < (int)u.size(); ++j) { int nx = u[j].first, ny = u[j].second; int val = dp[x][y] + abs(x - nx) + abs(y - ny); if (dp[nx][ny] > val) { dp[nx][ny] = val; } } dp[x][y] = INF; } } } } int ans = INF; for (int i = 0; i < (int)wh[1].size(); ++i) { ans = min(ans, dp[wh[1][i].first][wh[1][i].second] + abs(1 - wh[1][i].first) + abs(1 - wh[1][i].second)); } printf("%d\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1}; int arr[512][512], cnt[102400]; int dp[512][512], dis[512][512]; vector<pair<int, int> > pos[102400]; int main() { int n, m, p, enx, eny; scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", arr[i] + j); if (arr[i][j] == p) { enx = i; eny = j; } cnt[arr[i][j]]++; pos[arr[i][j]].push_back(make_pair(i, j)); } } memset(dp, 0x3F, sizeof(dp)); for (int i = 0; i < pos[1].size(); i++) dp[pos[1][i].first][pos[1][i].second] = pos[1][i].first + pos[1][i].second; for (int i = 2; i <= p; i++) { if (cnt[i] * cnt[i - 1] <= n * m) { for (int j = 0; j < pos[i - 1].size(); j++) { for (int k = 0; k < pos[i].size(); k++) { dp[pos[i][k].first][pos[i][k].second] = min(dp[pos[i][k].first][pos[i][k].second], dp[pos[i - 1][j].first][pos[i - 1][j].second] + ((pos[i][k].first - pos[i - 1][j].first) < 0 ? -(pos[i][k].first - pos[i - 1][j].first) : (pos[i][k].first - pos[i - 1][j].first)) + ((pos[i][k].second - pos[i - 1][j].second) < 0 ? -(pos[i][k].second - pos[i - 1][j].second) : (pos[i][k].second - pos[i - 1][j].second))); } } continue; } vector<pair<int, pair<int, int> > > app; memset(dis, 0x3F, sizeof(dis)); for (int j = 0; j < pos[i - 1].size(); j++) { app.push_back(make_pair(dp[pos[i - 1][j].first][pos[i - 1][j].second], pos[i - 1][j])); dis[pos[i - 1][j].first][pos[i - 1][j].second] = dp[pos[i - 1][j].first][pos[i - 1][j].second]; } sort(app.begin(), app.end()); queue<pair<int, int> > que; for (int j = 0; j < app.size(); j++) que.push(app[j].second); while (!que.empty()) { int x = que.front().first, y = que.front().second; que.pop(); for (int j = 0; j < 4; j++) { int newx = x + dx[j], newy = y + dy[j]; if (newx < 0 || newx >= n || newy < 0 || newy >= m || dis[x][y] + 1 >= dis[newx][newy]) continue; dis[newx][newy] = dis[x][y] + 1; que.push(make_pair(newx, newy)); } } for (int j = 0; j < pos[i].size(); j++) dp[pos[i][j].first][pos[i][j].second] = dis[pos[i][j].first][pos[i][j].second]; } printf("%d\n", dp[enx][eny]); return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: Vanya is in the palace that can be represented as a grid n Γ— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure. Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|. Input The first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m) β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively. Each of the following n lines contains m integers aij (1 ≀ aij ≀ p) β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p. Output Print one integer β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p. Examples Input 3 4 3 2 1 1 1 1 1 1 1 2 1 1 3 Output 5 Input 3 3 9 1 3 5 8 9 7 4 6 2 Output 22 Input 3 4 12 1 2 3 4 8 7 6 5 9 10 11 12 Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1}; int arr[512][512], cnt[102400]; int dp[512][512], dis[512][512]; vector<pair<int, int> > pos[102400]; int main() { int n, m, p, enx, eny; scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", arr[i] + j); if (arr[i][j] == p) { enx = i; eny = j; } cnt[arr[i][j]]++; pos[arr[i][j]].push_back(make_pair(i, j)); } } memset(dp, 0x3F, sizeof(dp)); for (int i = 0; i < pos[1].size(); i++) dp[pos[1][i].first][pos[1][i].second] = pos[1][i].first + pos[1][i].second; for (int i = 2; i <= p; i++) { if (cnt[i] * cnt[i - 1] <= n * m) { for (int j = 0; j < pos[i - 1].size(); j++) { for (int k = 0; k < pos[i].size(); k++) { dp[pos[i][k].first][pos[i][k].second] = min(dp[pos[i][k].first][pos[i][k].second], dp[pos[i - 1][j].first][pos[i - 1][j].second] + ((pos[i][k].first - pos[i - 1][j].first) < 0 ? -(pos[i][k].first - pos[i - 1][j].first) : (pos[i][k].first - pos[i - 1][j].first)) + ((pos[i][k].second - pos[i - 1][j].second) < 0 ? -(pos[i][k].second - pos[i - 1][j].second) : (pos[i][k].second - pos[i - 1][j].second))); } } continue; } vector<pair<int, pair<int, int> > > app; memset(dis, 0x3F, sizeof(dis)); for (int j = 0; j < pos[i - 1].size(); j++) { app.push_back(make_pair(dp[pos[i - 1][j].first][pos[i - 1][j].second], pos[i - 1][j])); dis[pos[i - 1][j].first][pos[i - 1][j].second] = dp[pos[i - 1][j].first][pos[i - 1][j].second]; } sort(app.begin(), app.end()); queue<pair<int, int> > que; for (int j = 0; j < app.size(); j++) que.push(app[j].second); while (!que.empty()) { int x = que.front().first, y = que.front().second; que.pop(); for (int j = 0; j < 4; j++) { int newx = x + dx[j], newy = y + dy[j]; if (newx < 0 || newx >= n || newy < 0 || newy >= m || dis[x][y] + 1 >= dis[newx][newy]) continue; dis[newx][newy] = dis[x][y] + 1; que.push(make_pair(newx, newy)); } } for (int j = 0; j < pos[i].size(); j++) dp[pos[i][j].first][pos[i][j].second] = dis[pos[i][j].first][pos[i][j].second]; } printf("%d\n", dp[enx][eny]); return 0; } ```