output
stringlengths
52
181k
instruction
stringlengths
296
182k
#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 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 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 MOD = 1000000007; const int MAX = 305; int dp[MAX][MAX]; int d[MAX][MAX]; vector<pair<int, int> > sq[MAX * MAX]; int n, m, p; int dist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } int ok(int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; } int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; bool comp(pair<int, int> a, pair<int, int> b) { return dp[a.first][a.second] < dp[b.first][b.second]; } int main() { scanf("%d %d %d", &n, &m, &p); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int k; scanf("%d", &k); sq[k].push_back(make_pair(i, j)); } } for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { dp[i][j] = MOD; } } for (pair<int, int> i : sq[1]) { dp[i.first][i.second] = i.first + i.second; } for (int i = 2; i < p + 1; i++) { if (sq[i].size() <= n) { for (pair<int, int> a : sq[i - 1]) { for (pair<int, int> b : sq[i]) { dp[b.first][b.second] = min(dp[b.first][b.second], dp[a.first][a.second] + dist(a, b)); } } } else { for (int a = 0; a < MAX; a++) { for (int b = 0; b < MAX; b++) { d[a][b] = MOD; } } queue<pair<int, pair<int, int> > > q; queue<pair<int, int> > q2; vector<pair<int, int> > v = sq[i - 1]; sort(v.begin(), v.end(), comp); for (pair<int, int> i : v) { q2.push(i); } q.push(make_pair(dp[v[0].first][v[0].second], v[0])); while (!q.empty()) { auto t = q.front(); if (!q2.empty()) { pair<int, int> orig = q2.front(); if (dp[orig.first][orig.second] <= t.first) { t = make_pair(dp[orig.first][orig.second], orig); q2.pop(); } else { q.pop(); } } else { q.pop(); } if (d[t.second.first][t.second.second] > t.first && d[t.second.first][t.second.second] != MOD) { continue; } d[t.second.first][t.second.second] = t.first; for (int a = 0; a < 4; a++) { int nx = t.second.first + dx[a]; int ny = t.second.second + dy[a]; if (ok(nx, ny) && d[nx][ny] == MOD) { d[nx][ny] = min(d[nx][ny], d[t.second.first][t.second.second] + 1); q.push(make_pair(d[nx][ny], make_pair(nx, ny))); } } } for (pair<int, int> b : sq[i]) { dp[b.first][b.second] = d[b.first][b.second]; } } } int ans = MOD; for (pair<int, int> i : sq[p]) { ans = min(ans, dp[i.first][i.second]); } printf("%d", ans); }
### 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 MOD = 1000000007; const int MAX = 305; int dp[MAX][MAX]; int d[MAX][MAX]; vector<pair<int, int> > sq[MAX * MAX]; int n, m, p; int dist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } int ok(int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; } int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; bool comp(pair<int, int> a, pair<int, int> b) { return dp[a.first][a.second] < dp[b.first][b.second]; } int main() { scanf("%d %d %d", &n, &m, &p); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int k; scanf("%d", &k); sq[k].push_back(make_pair(i, j)); } } for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { dp[i][j] = MOD; } } for (pair<int, int> i : sq[1]) { dp[i.first][i.second] = i.first + i.second; } for (int i = 2; i < p + 1; i++) { if (sq[i].size() <= n) { for (pair<int, int> a : sq[i - 1]) { for (pair<int, int> b : sq[i]) { dp[b.first][b.second] = min(dp[b.first][b.second], dp[a.first][a.second] + dist(a, b)); } } } else { for (int a = 0; a < MAX; a++) { for (int b = 0; b < MAX; b++) { d[a][b] = MOD; } } queue<pair<int, pair<int, int> > > q; queue<pair<int, int> > q2; vector<pair<int, int> > v = sq[i - 1]; sort(v.begin(), v.end(), comp); for (pair<int, int> i : v) { q2.push(i); } q.push(make_pair(dp[v[0].first][v[0].second], v[0])); while (!q.empty()) { auto t = q.front(); if (!q2.empty()) { pair<int, int> orig = q2.front(); if (dp[orig.first][orig.second] <= t.first) { t = make_pair(dp[orig.first][orig.second], orig); q2.pop(); } else { q.pop(); } } else { q.pop(); } if (d[t.second.first][t.second.second] > t.first && d[t.second.first][t.second.second] != MOD) { continue; } d[t.second.first][t.second.second] = t.first; for (int a = 0; a < 4; a++) { int nx = t.second.first + dx[a]; int ny = t.second.second + dy[a]; if (ok(nx, ny) && d[nx][ny] == MOD) { d[nx][ny] = min(d[nx][ny], d[t.second.first][t.second.second] + 1); q.push(make_pair(d[nx][ny], make_pair(nx, ny))); } } } for (pair<int, int> b : sq[i]) { dp[b.first][b.second] = d[b.first][b.second]; } } } int ans = MOD; for (pair<int, int> i : sq[p]) { ans = min(ans, dp[i.first][i.second]); } printf("%d", ans); } ```
#include <bits/stdc++.h> using namespace std; const int MAXN = 5e5 + 256; const char nxtl = '\n'; const double eps = (double)1e-9; template <typename T> inline bool updmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool updmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } int n, m, k, a[303][303]; vector<pair<int, int> > v[303 * 303]; set<pair<int, pair<int, int> > > S; int d[302][302], cnt[303 * 303]; int main() { scanf("%d%d%d", &n, &m, &k); 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)); d[i][j] = (int)1e9; } } int ans = (int)2e9; d[v[k].back().first][v[k].back().second] = 0; S.insert(make_pair(0, v[k].back())); while (!S.empty()) { const int &clr = a[S.begin()->second.first][S.begin()->second.second]; const auto id = S.begin()->second; S.erase(S.begin()); if (clock() * 1.0 / CLOCKS_PER_SEC > 1.45999) break; if (cnt[clr] > 10000) continue; if (clr == 1) { updmin(ans, id.first - 1 + id.second - 1 + d[id.first][id.second]); continue; } cnt[clr]++; for (auto &to : v[clr - 1]) { int D = abs(to.first - id.first) + abs(to.second - id.second); if (D + d[id.first][id.second] < d[to.first][to.second]) { S.erase(make_pair(d[to.first][to.second], to)); d[to.first][to.second] = D + d[id.first][id.second]; S.insert(make_pair(d[to.first][to.second], to)); } } } printf("%d\n", ans); 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 = 5e5 + 256; const char nxtl = '\n'; const double eps = (double)1e-9; template <typename T> inline bool updmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool updmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } int n, m, k, a[303][303]; vector<pair<int, int> > v[303 * 303]; set<pair<int, pair<int, int> > > S; int d[302][302], cnt[303 * 303]; int main() { scanf("%d%d%d", &n, &m, &k); 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)); d[i][j] = (int)1e9; } } int ans = (int)2e9; d[v[k].back().first][v[k].back().second] = 0; S.insert(make_pair(0, v[k].back())); while (!S.empty()) { const int &clr = a[S.begin()->second.first][S.begin()->second.second]; const auto id = S.begin()->second; S.erase(S.begin()); if (clock() * 1.0 / CLOCKS_PER_SEC > 1.45999) break; if (cnt[clr] > 10000) continue; if (clr == 1) { updmin(ans, id.first - 1 + id.second - 1 + d[id.first][id.second]); continue; } cnt[clr]++; for (auto &to : v[clr - 1]) { int D = abs(to.first - id.first) + abs(to.second - id.second); if (D + d[id.first][id.second] < d[to.first][to.second]) { S.erase(make_pair(d[to.first][to.second], to)); d[to.first][to.second] = D + d[id.first][id.second]; S.insert(make_pair(d[to.first][to.second], to)); } } } printf("%d\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; int m, n; const int inf = 0x3f3f3f3f; struct node { int x, y; node(int x = 0, int y = 0) { this->x = x; this->y = y; } }; const int mx[6] = {0, 1, 0, -1, 0}; const int my[6] = {0, 0, 1, 0, -1}; vector<node> f[90011]; int gg[301][301]; int g[301][301], x, y; int p; int dp[333][333]; struct pnode { int x, y, w; pnode(int xx = 0, int yy = 0, int ww = 0) { x = xx; y = yy; w = ww; } bool operator<(const pnode &head) const { return head.w < w; } }; priority_queue<pnode> q; int main() { scanf("%d%d%d", &m, &n, &p); for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { dp[i][j] = inf; scanf("%d", &g[i][j]); f[g[i][j]].push_back(node(i, j)); } f[0].push_back(node(1, 1)); for (int ww = 1; ww <= p; ww++) { if ((long long)f[ww - 1].size() * f[ww].size() <= (long long)m * n * 8) for (int i = 0; i < f[ww - 1].size(); i++) for (int j = 0; j < f[ww].size(); j++) { int &tx = f[ww][j].x; int &ty = f[ww][j].y; int &fx = f[ww - 1][i].x; int &fy = f[ww - 1][i].y; if (ww == 1) dp[tx][ty] = abs(fx - tx) + abs(fy - ty); else dp[tx][ty] = min(dp[tx][ty], dp[fx][fy] + abs(fx - tx) + abs(fy - ty)); } else { memset(gg, -1, sizeof(gg)); while (!q.empty()) q.pop(); for (int i = 0; i < f[ww - 1].size(); i++) { int x = f[ww - 1][i].x; int y = f[ww - 1][i].y; q.push(pnode(x, y, dp[x][y])); gg[x][y] = dp[x][y]; } while (!q.empty()) { pnode u = q.top(); q.pop(); if (g[u.x][u.y] == ww) dp[u.x][u.y] = min(dp[u.x][u.y], gg[u.x][u.y]); for (int e = 1; e <= 4; e++) { int tx = u.x + mx[e]; int ty = u.y + my[e]; if (tx >= 1 && tx <= m && ty >= 1 && ty <= n && gg[tx][ty] == -1) { gg[tx][ty] = gg[u.x][u.y] + 1; q.push(pnode(tx, ty, gg[tx][ty])); } } } } } int ans = inf; for (int i = 0; i < f[p].size(); i++) ans = min(ans, dp[f[p][i].x][f[p][i].y]); cout << ans << 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> using namespace std; int m, n; const int inf = 0x3f3f3f3f; struct node { int x, y; node(int x = 0, int y = 0) { this->x = x; this->y = y; } }; const int mx[6] = {0, 1, 0, -1, 0}; const int my[6] = {0, 0, 1, 0, -1}; vector<node> f[90011]; int gg[301][301]; int g[301][301], x, y; int p; int dp[333][333]; struct pnode { int x, y, w; pnode(int xx = 0, int yy = 0, int ww = 0) { x = xx; y = yy; w = ww; } bool operator<(const pnode &head) const { return head.w < w; } }; priority_queue<pnode> q; int main() { scanf("%d%d%d", &m, &n, &p); for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { dp[i][j] = inf; scanf("%d", &g[i][j]); f[g[i][j]].push_back(node(i, j)); } f[0].push_back(node(1, 1)); for (int ww = 1; ww <= p; ww++) { if ((long long)f[ww - 1].size() * f[ww].size() <= (long long)m * n * 8) for (int i = 0; i < f[ww - 1].size(); i++) for (int j = 0; j < f[ww].size(); j++) { int &tx = f[ww][j].x; int &ty = f[ww][j].y; int &fx = f[ww - 1][i].x; int &fy = f[ww - 1][i].y; if (ww == 1) dp[tx][ty] = abs(fx - tx) + abs(fy - ty); else dp[tx][ty] = min(dp[tx][ty], dp[fx][fy] + abs(fx - tx) + abs(fy - ty)); } else { memset(gg, -1, sizeof(gg)); while (!q.empty()) q.pop(); for (int i = 0; i < f[ww - 1].size(); i++) { int x = f[ww - 1][i].x; int y = f[ww - 1][i].y; q.push(pnode(x, y, dp[x][y])); gg[x][y] = dp[x][y]; } while (!q.empty()) { pnode u = q.top(); q.pop(); if (g[u.x][u.y] == ww) dp[u.x][u.y] = min(dp[u.x][u.y], gg[u.x][u.y]); for (int e = 1; e <= 4; e++) { int tx = u.x + mx[e]; int ty = u.y + my[e]; if (tx >= 1 && tx <= m && ty >= 1 && ty <= n && gg[tx][ty] == -1) { gg[tx][ty] = gg[u.x][u.y] + 1; q.push(pnode(tx, ty, gg[tx][ty])); } } } } } int ans = inf; for (int i = 0; i < f[p].size(); i++) ans = min(ans, dp[f[p][i].x][f[p][i].y]); cout << ans << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; template <class t> inline t read(t &x) { char c = getchar(); bool f = 0; x = 0; while (!isdigit(c)) f |= c == '-', c = getchar(); while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48), c = getchar(); if (f) x = -x; return x; } 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); } } const int N = 305; int n, m, k; long long ans = 1e16, f[N][N], tr[N][N], tr2[N][N]; bool exi[N][N], exi2[N][N]; vector<pair<int, int> > col[N * N], cl, cl2; void up(int first, int second, long long v) { while (second <= m) { if (!exi[first][second]) exi[first][second] = 1, cl.push_back(pair<int, int>(first, second)); tr[first][second] = min(tr[first][second], v); second += (second & (-second)); } } long long que(int first, int second) { long long res = 1e16; while (second) { res = min(res, tr[first][second]); second -= (second & (-second)); } return res; } void up2(int first, int second, long long v) { while (second) { if (!exi2[first][second]) exi2[first][second] = 1, cl2.push_back(pair<int, int>(first, second)); tr2[first][second] = min(tr2[first][second], v); second -= (second & (-second)); } } long long que2(int first, int second) { long long res = 1e16; while (second <= m) { res = min(res, tr2[first][second]); second += (second & (-second)); } return res; } signed main() { read(n); read(m); read(k); for (int i = 1, c; i <= n; i++) for (int j = 1; j <= m; j++) col[read(c)].push_back(pair<int, int>(i, j)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) tr[i][j] = tr2[i][j] = 1e16; up(1, 1, -1); for (int c = 1; c <= k; c++) { for (int id = 0; id < col[c].size(); id++) { int first = col[c][id].first, second = col[c][id].second; f[first][second] = 1e16; for (int i = 1; i <= n; i++) f[first][second] = min(f[first][second], min(que(i, second) + second, que2(i, second + 1) - second) + abs(first - i)); if (c == k) ans = min(ans, f[first][second]); } for (int i = 0; i < cl.size(); i++) { int first = cl[i].first, second = cl[i].second; exi[first][second] = 0; tr[first][second] = 1e16; } cl.clear(); for (int i = 0; i < cl2.size(); i++) { int first = cl2[i].first, second = cl2[i].second; exi2[first][second] = 0; tr2[first][second] = 1e16; } cl2.clear(); for (int id = 0; id < col[c].size(); id++) { int first = col[c][id].first, second = col[c][id].second; up(first, second, f[first][second] - second); up2(first, second, f[first][second] + second); } } write(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; template <class t> inline t read(t &x) { char c = getchar(); bool f = 0; x = 0; while (!isdigit(c)) f |= c == '-', c = getchar(); while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48), c = getchar(); if (f) x = -x; return x; } 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); } } const int N = 305; int n, m, k; long long ans = 1e16, f[N][N], tr[N][N], tr2[N][N]; bool exi[N][N], exi2[N][N]; vector<pair<int, int> > col[N * N], cl, cl2; void up(int first, int second, long long v) { while (second <= m) { if (!exi[first][second]) exi[first][second] = 1, cl.push_back(pair<int, int>(first, second)); tr[first][second] = min(tr[first][second], v); second += (second & (-second)); } } long long que(int first, int second) { long long res = 1e16; while (second) { res = min(res, tr[first][second]); second -= (second & (-second)); } return res; } void up2(int first, int second, long long v) { while (second) { if (!exi2[first][second]) exi2[first][second] = 1, cl2.push_back(pair<int, int>(first, second)); tr2[first][second] = min(tr2[first][second], v); second -= (second & (-second)); } } long long que2(int first, int second) { long long res = 1e16; while (second <= m) { res = min(res, tr2[first][second]); second += (second & (-second)); } return res; } signed main() { read(n); read(m); read(k); for (int i = 1, c; i <= n; i++) for (int j = 1; j <= m; j++) col[read(c)].push_back(pair<int, int>(i, j)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) tr[i][j] = tr2[i][j] = 1e16; up(1, 1, -1); for (int c = 1; c <= k; c++) { for (int id = 0; id < col[c].size(); id++) { int first = col[c][id].first, second = col[c][id].second; f[first][second] = 1e16; for (int i = 1; i <= n; i++) f[first][second] = min(f[first][second], min(que(i, second) + second, que2(i, second + 1) - second) + abs(first - i)); if (c == k) ans = min(ans, f[first][second]); } for (int i = 0; i < cl.size(); i++) { int first = cl[i].first, second = cl[i].second; exi[first][second] = 0; tr[first][second] = 1e16; } cl.clear(); for (int i = 0; i < cl2.size(); i++) { int first = cl2[i].first, second = cl2[i].second; exi2[first][second] = 0; tr2[first][second] = 1e16; } cl2.clear(); for (int id = 0; id < col[c].size(); id++) { int first = col[c][id].first, second = col[c][id].second; up(first, second, f[first][second] - second); up2(first, second, f[first][second] + second); } } write(ans); } ```
#include <bits/stdc++.h> #pragma GCC optimize(2) 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 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> #pragma GCC optimize(2) 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; 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 <= 600; 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 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 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 <= 600; 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 MAXN = 300 + 10; const int MAXV = MAXN * MAXN; const int INF = 1e9 + 69; int n, m, p, a[MAXN][MAXN]; int dr[] = {-1, 0, 0, 1}; int dc[] = {0, -1, 1, 0}; void mini(int& x, int y) { x = min(x, y); } bool on_grid(int i, int j) { return 0 <= i && i < n && 0 <= j && j < m; } int distance(const pair<int, int>& A, const pair<int, int>& B) { return abs(A.first - B.first) + abs(A.second - B.second); } vector<pair<int, int>> pos[MAXV]; vector<int> dp[MAXV]; int idx[MAXN][MAXN]; const int SQ = 369; struct cmp { bool operator()(const array<int, 3>& A, const array<int, 3>& B) { return A[0] > B[0]; } }; priority_queue<array<int, 3>, vector<array<int, 3>>, cmp> pq; int d[MAXN][MAXN]; void dij(int xx) { while (!pq.empty()) { auto [D, i, j] = pq.top(); pq.pop(); if (D ^ d[i][j]) continue; for (int k = 0; k < 4; k++) { int r = i + dr[k], c = j + dc[k]; if (!on_grid(r, c)) continue; if (d[r][c] > D + 1) { d[r][c] = D + 1; pq.push({d[r][c], r, c}); if (a[r][c] == xx + 1) { mini(dp[xx + 1][idx[r][c]], d[r][c]); } } } } } void solve() { cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> a[i][j]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) idx[i][j] = pos[a[i][j]].size(), pos[a[i][j]].emplace_back(i, j); for (int x = 1; x <= p; x++) dp[x].resize(pos[x].size(), INF); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] == 1) dp[1][idx[i][j]] = distance(pair<int, int>(0, 0), pair<int, int>(i, j)); for (int x = 1; x < p; x++) { int sz = dp[x].size(); if (sz * dp[x + 1].size() < (MAXN * MAXN << 3)) { for (int i = 0; i < sz; i++) for (int j = 0; j < (int)dp[x + 1].size(); j++) mini(dp[x + 1][j], dp[x][i] + distance(pos[x][i], pos[x + 1][j])); } else { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) d[i][j] = INF; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] == x) d[i][j] = dp[x][idx[i][j]], pq.push({d[i][j], i, j}); dij(x); } } cout << dp[p][0] << "\n"; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int te = 1; for (int w = 1; w <= te; w++) { 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 MAXN = 300 + 10; const int MAXV = MAXN * MAXN; const int INF = 1e9 + 69; int n, m, p, a[MAXN][MAXN]; int dr[] = {-1, 0, 0, 1}; int dc[] = {0, -1, 1, 0}; void mini(int& x, int y) { x = min(x, y); } bool on_grid(int i, int j) { return 0 <= i && i < n && 0 <= j && j < m; } int distance(const pair<int, int>& A, const pair<int, int>& B) { return abs(A.first - B.first) + abs(A.second - B.second); } vector<pair<int, int>> pos[MAXV]; vector<int> dp[MAXV]; int idx[MAXN][MAXN]; const int SQ = 369; struct cmp { bool operator()(const array<int, 3>& A, const array<int, 3>& B) { return A[0] > B[0]; } }; priority_queue<array<int, 3>, vector<array<int, 3>>, cmp> pq; int d[MAXN][MAXN]; void dij(int xx) { while (!pq.empty()) { auto [D, i, j] = pq.top(); pq.pop(); if (D ^ d[i][j]) continue; for (int k = 0; k < 4; k++) { int r = i + dr[k], c = j + dc[k]; if (!on_grid(r, c)) continue; if (d[r][c] > D + 1) { d[r][c] = D + 1; pq.push({d[r][c], r, c}); if (a[r][c] == xx + 1) { mini(dp[xx + 1][idx[r][c]], d[r][c]); } } } } } void solve() { cin >> n >> m >> p; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> a[i][j]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) idx[i][j] = pos[a[i][j]].size(), pos[a[i][j]].emplace_back(i, j); for (int x = 1; x <= p; x++) dp[x].resize(pos[x].size(), INF); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] == 1) dp[1][idx[i][j]] = distance(pair<int, int>(0, 0), pair<int, int>(i, j)); for (int x = 1; x < p; x++) { int sz = dp[x].size(); if (sz * dp[x + 1].size() < (MAXN * MAXN << 3)) { for (int i = 0; i < sz; i++) for (int j = 0; j < (int)dp[x + 1].size(); j++) mini(dp[x + 1][j], dp[x][i] + distance(pos[x][i], pos[x + 1][j])); } else { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) d[i][j] = INF; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] == x) d[i][j] = dp[x][idx[i][j]], pq.push({d[i][j], i, j}); dij(x); } } cout << dp[p][0] << "\n"; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int te = 1; for (int w = 1; w <= te; w++) { solve(); } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3f; const int N = 3e2; int n, m, k, a[N + 7][N + 7]; struct node { int first, second, g; node(int X = 0, int Y = 0, int G = 0) { first = X, second = Y, g = G; } }; vector<node> w[N * N + 7]; int d[N + 7][N + 7]; int tx[] = {0, 0, -1, 1}, ty[] = {-1, 1, 0, 0}; int ok(int first, int second) { return 1 <= first && first <= n && 1 <= second && second <= m; } void Bfs(vector<node>& s) { vector<node> q; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) d[i][j] = inf; int sc = -1; q.push_back(s[++sc]); for (int i = 0; i < int((q).size()); i++) { node v = q[i]; while (sc + 1 < int((s).size()) && s[sc + 1].g <= v.g) q.push_back(s[++sc]); for (int t = 0; t < 4; t++) { node u = node(v.first + tx[t], v.second + ty[t]); if (ok(u.first, u.second) && v.g + 1 < d[u.first][u.second]) d[u.first][u.second] = u.g = v.g + 1, q.push_back(u); } } } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) w[a[i][j]].push_back(node(i, j, i + j - 2)); else w[a[i][j]].push_back(node(i, j, inf)); } for (int key = 2; key <= k; key++) { if (int((w[key - 1]).size()) * int((w[key]).size()) <= n * m) { for (node& u : w[key]) for (node v : w[key - 1]) u.g = min(u.g, v.g + abs(u.first - v.first) + abs(u.second - v.second)); } else { vector<node> s; for (node v : w[key - 1]) s.push_back(v); Bfs(s); for (node& u : w[key]) u.g = d[u.first][u.second]; } } printf("%d\n", w[k][0].g); 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 inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3f; const int N = 3e2; int n, m, k, a[N + 7][N + 7]; struct node { int first, second, g; node(int X = 0, int Y = 0, int G = 0) { first = X, second = Y, g = G; } }; vector<node> w[N * N + 7]; int d[N + 7][N + 7]; int tx[] = {0, 0, -1, 1}, ty[] = {-1, 1, 0, 0}; int ok(int first, int second) { return 1 <= first && first <= n && 1 <= second && second <= m; } void Bfs(vector<node>& s) { vector<node> q; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) d[i][j] = inf; int sc = -1; q.push_back(s[++sc]); for (int i = 0; i < int((q).size()); i++) { node v = q[i]; while (sc + 1 < int((s).size()) && s[sc + 1].g <= v.g) q.push_back(s[++sc]); for (int t = 0; t < 4; t++) { node u = node(v.first + tx[t], v.second + ty[t]); if (ok(u.first, u.second) && v.g + 1 < d[u.first][u.second]) d[u.first][u.second] = u.g = v.g + 1, q.push_back(u); } } } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) w[a[i][j]].push_back(node(i, j, i + j - 2)); else w[a[i][j]].push_back(node(i, j, inf)); } for (int key = 2; key <= k; key++) { if (int((w[key - 1]).size()) * int((w[key]).size()) <= n * m) { for (node& u : w[key]) for (node v : w[key - 1]) u.g = min(u.g, v.g + abs(u.first - v.first) + abs(u.second - v.second)); } else { vector<node> s; for (node v : w[key - 1]) s.push_back(v); Bfs(s); for (node& u : w[key]) u.g = d[u.first][u.second]; } } printf("%d\n", w[k][0].g); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 305; int dp[maxn][maxn], mat[maxn][maxn]; int cnt[maxn * maxn], inq[maxn][maxn], d[maxn][maxn]; vector<pair<int, int> > G[maxn * maxn]; int n, m, p; inline int get_dis(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, -1, 1}; void init() { memset(dp, 0x7f, sizeof(dp)); memset(cnt, 0, sizeof(cnt)); } int main() { while (scanf("%d%d%d", &n, &m, &p) == 3 && n) { init(); int xt, yt; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &mat[i][j]); if (mat[i][j] == 1) dp[i][j] = get_dis(0, 0, i, j); if (mat[i][j] == p) xt = i, yt = j; cnt[mat[i][j]]++; G[mat[i][j]].push_back(make_pair(i, j)); } } for (int i = 2; i <= p; i++) { if (cnt[i - 1] * cnt[i] <= m * n) { for (int j = 0; j < G[i].size(); j++) { int x2 = G[i][j].first, y2 = G[i][j].second; for (int k = 0; k < G[i - 1].size(); k++) { int x1 = G[i - 1][k].first, y1 = G[i - 1][k].second; dp[x2][y2] = min(dp[x2][y2], dp[x1][y1] + get_dis(x1, y1, x2, y2)); } } } else { memset(d, 0x7f, sizeof(d)); memset(inq, 0, sizeof(inq)); queue<pair<int, int> > Q; for (int j = 0; j < G[i - 1].size(); j++) { pair<int, int> u = G[i - 1][j]; d[u.first][u.second] = dp[u.first][u.second], inq[u.first][u.second] = 1; Q.push(make_pair(u.first, u.second)); } while (!Q.empty()) { pair<int, int> u = Q.front(); Q.pop(); inq[u.first][u.second] = 0; if (mat[u.first][u.second] == i) dp[u.first][u.second] = min(dp[u.first][u.second], d[u.first][u.second]); for (int j = 0; j < 4; j++) { int x = u.first + dx[j], y = u.second + dy[j]; if (x < 0 || x >= n || y < 0 || y >= m) continue; if (d[x][y] > d[u.first][u.second] + 1) { d[x][y] = d[u.first][u.second] + 1; if (!inq[x][y]) inq[x][y] = 1, Q.push(make_pair(x, y)); } } } } } printf("%d\n", dp[xt][yt]); } 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 = 305; int dp[maxn][maxn], mat[maxn][maxn]; int cnt[maxn * maxn], inq[maxn][maxn], d[maxn][maxn]; vector<pair<int, int> > G[maxn * maxn]; int n, m, p; inline int get_dis(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, -1, 1}; void init() { memset(dp, 0x7f, sizeof(dp)); memset(cnt, 0, sizeof(cnt)); } int main() { while (scanf("%d%d%d", &n, &m, &p) == 3 && n) { init(); int xt, yt; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &mat[i][j]); if (mat[i][j] == 1) dp[i][j] = get_dis(0, 0, i, j); if (mat[i][j] == p) xt = i, yt = j; cnt[mat[i][j]]++; G[mat[i][j]].push_back(make_pair(i, j)); } } for (int i = 2; i <= p; i++) { if (cnt[i - 1] * cnt[i] <= m * n) { for (int j = 0; j < G[i].size(); j++) { int x2 = G[i][j].first, y2 = G[i][j].second; for (int k = 0; k < G[i - 1].size(); k++) { int x1 = G[i - 1][k].first, y1 = G[i - 1][k].second; dp[x2][y2] = min(dp[x2][y2], dp[x1][y1] + get_dis(x1, y1, x2, y2)); } } } else { memset(d, 0x7f, sizeof(d)); memset(inq, 0, sizeof(inq)); queue<pair<int, int> > Q; for (int j = 0; j < G[i - 1].size(); j++) { pair<int, int> u = G[i - 1][j]; d[u.first][u.second] = dp[u.first][u.second], inq[u.first][u.second] = 1; Q.push(make_pair(u.first, u.second)); } while (!Q.empty()) { pair<int, int> u = Q.front(); Q.pop(); inq[u.first][u.second] = 0; if (mat[u.first][u.second] == i) dp[u.first][u.second] = min(dp[u.first][u.second], d[u.first][u.second]); for (int j = 0; j < 4; j++) { int x = u.first + dx[j], y = u.second + dy[j]; if (x < 0 || x >= n || y < 0 || y >= m) continue; if (d[x][y] > d[u.first][u.second] + 1) { d[x][y] = d[u.first][u.second] + 1; if (!inq[x][y]) inq[x][y] = 1, Q.push(make_pair(x, y)); } } } } } printf("%d\n", dp[xt][yt]); } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 310; int a[N][N], dp[N][N]; vector<pair<int, int> > g[N * N]; const int inf = 1e9; int vis[N]; 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++) { 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 - 2; } else { dp[i][j] = inf; } } } for (int i = 1; i < p; i++) { vector<int> cur[m + 5]; for (auto it : g[i + 1]) { cur[it.second].push_back(it.first); } for (auto it : g[i]) { vis[it.first] = i; } for (int j = 1; j <= n; j++) { if (vis[j] == i) { int best = inf; for (int k = 1; k <= m; k++) { best++; if (a[j][k] == i) { best = min(best, dp[j][k]); } for (auto it : cur[k]) { dp[it][k] = min(dp[it][k], best + abs(it - j)); } } best = inf; for (int k = m; k >= 1; k--) { best++; if (a[j][k] == i) { best = min(best, dp[j][k]); } for (auto it : cur[k]) { dp[it][k] = min(dp[it][k], best + abs(it - j)); } } } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == p) { printf("%d\n", dp[i][j]); } } } }
### 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 N = 310; int a[N][N], dp[N][N]; vector<pair<int, int> > g[N * N]; const int inf = 1e9; int vis[N]; 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++) { 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 - 2; } else { dp[i][j] = inf; } } } for (int i = 1; i < p; i++) { vector<int> cur[m + 5]; for (auto it : g[i + 1]) { cur[it.second].push_back(it.first); } for (auto it : g[i]) { vis[it.first] = i; } for (int j = 1; j <= n; j++) { if (vis[j] == i) { int best = inf; for (int k = 1; k <= m; k++) { best++; if (a[j][k] == i) { best = min(best, dp[j][k]); } for (auto it : cur[k]) { dp[it][k] = min(dp[it][k], best + abs(it - j)); } } best = inf; for (int k = m; k >= 1; k--) { best++; if (a[j][k] == i) { best = min(best, dp[j][k]); } for (auto it : cur[k]) { dp[it][k] = min(dp[it][k], best + abs(it - j)); } } } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == p) { printf("%d\n", dp[i][j]); } } } } ```
#include <bits/stdc++.h> using namespace std; const int N = (int)1e5 + 17; const int MX = (int)1e6 + 17; const int MOD = (int)1e9 + 7; const long long oo = LLONG_MAX; const int INF = INT_MAX; const long double Pi = 3.14159265358979323846264338327950288419716939937510; const int di[4] = {-1, 0, 1, 0}; const int dj[4] = {0, 1, 0, -1}; inline long long IN() { long long x = 0, ch = getchar(), f = 1; while (!isdigit(ch) && (ch != '-') && (ch != EOF)) ch = getchar(); if (ch == '-') { f = -1; ch = getchar(); } while (isdigit(ch)) { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); } return x * f; } inline void OUT(long long x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) OUT(x / 10), putchar(x % 10 + '0'); else putchar(x + '0'); } void IOI2017() {} int n, m, p, x; vector<pair<int, pair<int, int> > > G[N]; int Get(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } int main() { n = IN(), m = IN(), p = IN(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { x = IN(); G[x].push_back({MOD, {i, j}}); } } G[0].push_back({0, {1, 1}}); for (int i = 1; i <= p; i++) { sort(G[i - 1].begin(), G[i - 1].end()); for (int j = 0; j < (int)G[i].size(); j++) { for (int k = 0; k < min((int)G[i - 1].size(), 1000); k++) { G[i][j].first = min(G[i][j].first, G[i - 1][k].first + Get({G[i][j].second.first, G[i][j].second.second}, {G[i - 1][k].second.first, G[i - 1][k].second.second})); } } } cout << G[p][0].first; 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 = (int)1e5 + 17; const int MX = (int)1e6 + 17; const int MOD = (int)1e9 + 7; const long long oo = LLONG_MAX; const int INF = INT_MAX; const long double Pi = 3.14159265358979323846264338327950288419716939937510; const int di[4] = {-1, 0, 1, 0}; const int dj[4] = {0, 1, 0, -1}; inline long long IN() { long long x = 0, ch = getchar(), f = 1; while (!isdigit(ch) && (ch != '-') && (ch != EOF)) ch = getchar(); if (ch == '-') { f = -1; ch = getchar(); } while (isdigit(ch)) { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); } return x * f; } inline void OUT(long long x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) OUT(x / 10), putchar(x % 10 + '0'); else putchar(x + '0'); } void IOI2017() {} int n, m, p, x; vector<pair<int, pair<int, int> > > G[N]; int Get(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } int main() { n = IN(), m = IN(), p = IN(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { x = IN(); G[x].push_back({MOD, {i, j}}); } } G[0].push_back({0, {1, 1}}); for (int i = 1; i <= p; i++) { sort(G[i - 1].begin(), G[i - 1].end()); for (int j = 0; j < (int)G[i].size(); j++) { for (int k = 0; k < min((int)G[i - 1].size(), 1000); k++) { G[i][j].first = min(G[i][j].first, G[i - 1][k].first + Get({G[i][j].second.first, G[i][j].second.second}, {G[i - 1][k].second.first, G[i - 1][k].second.second})); } } } cout << G[p][0].first; return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p; int board[310][310], bfs_board[310][310], dp[310][310]; vector<vector<pair<int, int> > > coords; bool visited[310][310]; bool valid(int i, int j) { if (i >= 1 && i <= n && j >= 1 && j <= m) return true; else return false; } queue<pair<int, int> > q; queue<int> f; vector<pair<int, pair<int, int> > > v; int idx_v; void insert(int i, int j, int fit) { if (valid(i, j) && !visited[i][j]) { visited[i][j] = true; q.push(pair<int, int>(i, j)); f.push(fit + 1); bfs_board[i][j] = fit + 1; while (idx_v < (int)v.size() && v[idx_v].first == (fit + 1)) { int a = (v[idx_v].second).first, b = (v[idx_v].second).second; if (!visited[a][b]) { visited[a][b] = true; bfs_board[a][b] = fit + 1; q.push(v[idx_v].second); f.push(v[idx_v].first); } idx_v++; } } } void bfs(int x) { while (!q.empty()) q.pop(); while (!f.empty()) f.pop(); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) visited[i][j] = false; int min_dp = INFINITY; for (int i = 0; i < (int)coords[x].size(); i++) { int a = coords[x][i].first, b = coords[x][i].second; min_dp = min(min_dp, dp[a][b]); } v.clear(); idx_v = 0; for (int i = 0; i < (int)coords[x].size(); i++) { int a = coords[x][i].first, b = coords[x][i].second; if (dp[a][b] == min_dp) { q.push(coords[x][i]); f.push(dp[a][b]); visited[a][b] = true; bfs_board[a][b] = dp[a][b]; } else { v.push_back(pair<int, pair<int, int> >(dp[a][b], coords[x][i])); } } sort(v.begin(), v.end()); while (!q.empty()) { pair<int, int> aux = q.front(); q.pop(); int i = aux.first, j = aux.second; int fit = f.front(); f.pop(); insert(i - 1, j, fit); insert(i, j - 1, fit); insert(i + 1, j, fit); insert(i, j + 1, fit); } for (int i = 0; i < (int)coords[x + 1].size(); i++) { int a = coords[x + 1][i].first, b = coords[x + 1][i].second; dp[a][b] = bfs_board[a][b]; } } int main() { scanf("%d %d %d", &n, &m, &p); coords.resize(p + 1); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &board[i][j]); coords[board[i][j]].push_back(pair<int, int>(i, j)); } } for (int i = 0; i < (int)coords[1].size(); i++) { int a = coords[1][i].first, b = coords[1][i].second; dp[a][b] = a + b - 2; } for (int x = 1; x < p; x++) { if ((int)coords[x].size() * coords[x + 1].size() > m * n) bfs(x); else { for (int i = 0; i < (int)coords[x + 1].size(); i++) { int a1 = coords[x + 1][i].first, b1 = coords[x + 1][i].second; dp[a1][b1] = INFINITY; for (int j = 0; j < (int)coords[x].size(); j++) { int a2 = coords[x][j].first, b2 = coords[x][j].second; dp[a1][b1] = min(dp[a1][b1], dp[a2][b2] + abs(a2 - a1) + abs(b2 - b1)); } } } } int solution = INFINITY; for (int i = 0; i < (int)coords[p].size(); i++) { int a = coords[p][i].first, b = coords[p][i].second; solution = min(solution, dp[a][b]); } printf("%d\n", solution); }
### 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 n, m, p; int board[310][310], bfs_board[310][310], dp[310][310]; vector<vector<pair<int, int> > > coords; bool visited[310][310]; bool valid(int i, int j) { if (i >= 1 && i <= n && j >= 1 && j <= m) return true; else return false; } queue<pair<int, int> > q; queue<int> f; vector<pair<int, pair<int, int> > > v; int idx_v; void insert(int i, int j, int fit) { if (valid(i, j) && !visited[i][j]) { visited[i][j] = true; q.push(pair<int, int>(i, j)); f.push(fit + 1); bfs_board[i][j] = fit + 1; while (idx_v < (int)v.size() && v[idx_v].first == (fit + 1)) { int a = (v[idx_v].second).first, b = (v[idx_v].second).second; if (!visited[a][b]) { visited[a][b] = true; bfs_board[a][b] = fit + 1; q.push(v[idx_v].second); f.push(v[idx_v].first); } idx_v++; } } } void bfs(int x) { while (!q.empty()) q.pop(); while (!f.empty()) f.pop(); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) visited[i][j] = false; int min_dp = INFINITY; for (int i = 0; i < (int)coords[x].size(); i++) { int a = coords[x][i].first, b = coords[x][i].second; min_dp = min(min_dp, dp[a][b]); } v.clear(); idx_v = 0; for (int i = 0; i < (int)coords[x].size(); i++) { int a = coords[x][i].first, b = coords[x][i].second; if (dp[a][b] == min_dp) { q.push(coords[x][i]); f.push(dp[a][b]); visited[a][b] = true; bfs_board[a][b] = dp[a][b]; } else { v.push_back(pair<int, pair<int, int> >(dp[a][b], coords[x][i])); } } sort(v.begin(), v.end()); while (!q.empty()) { pair<int, int> aux = q.front(); q.pop(); int i = aux.first, j = aux.second; int fit = f.front(); f.pop(); insert(i - 1, j, fit); insert(i, j - 1, fit); insert(i + 1, j, fit); insert(i, j + 1, fit); } for (int i = 0; i < (int)coords[x + 1].size(); i++) { int a = coords[x + 1][i].first, b = coords[x + 1][i].second; dp[a][b] = bfs_board[a][b]; } } int main() { scanf("%d %d %d", &n, &m, &p); coords.resize(p + 1); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &board[i][j]); coords[board[i][j]].push_back(pair<int, int>(i, j)); } } for (int i = 0; i < (int)coords[1].size(); i++) { int a = coords[1][i].first, b = coords[1][i].second; dp[a][b] = a + b - 2; } for (int x = 1; x < p; x++) { if ((int)coords[x].size() * coords[x + 1].size() > m * n) bfs(x); else { for (int i = 0; i < (int)coords[x + 1].size(); i++) { int a1 = coords[x + 1][i].first, b1 = coords[x + 1][i].second; dp[a1][b1] = INFINITY; for (int j = 0; j < (int)coords[x].size(); j++) { int a2 = coords[x][j].first, b2 = coords[x][j].second; dp[a1][b1] = min(dp[a1][b1], dp[a2][b2] + abs(a2 - a1) + abs(b2 - b1)); } } } } int solution = INFINITY; for (int i = 0; i < (int)coords[p].size(); i++) { int a = coords[p][i].first, b = coords[p][i].second; solution = min(solution, dp[a][b]); } printf("%d\n", solution); } ```
#include <bits/stdc++.h> using namespace std; struct node { int x, y; }; vector<node> P[305 * 305]; int n, m, K, X, Y, mp[305][305], dp[305][305], L[2][305][305], R[2][305][305]; void Min(int &a, int b) { if (a == -1 || a > b) a = b; } int MIN(int a, int b) { if (a == -1) return b; if (b == -1) return a; return min(a, b); } int main() { scanf("%d%d%d", &n, &m, &K); int cur = 0; memset(dp, -1, sizeof(dp)); memset(L[cur], -1, sizeof(L[cur])); memset(R[cur], -1, sizeof(R[cur])); memset(L[cur ^ 1], -1, sizeof(L[cur])); memset(R[cur ^ 1], -1, sizeof(R[cur])); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) scanf("%d", &mp[i][j]); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { node tmp; tmp.x = i; tmp.y = j; P[mp[i][j]].push_back(tmp); if (mp[i][j] == 1) { dp[i][j] = i + j - 2; L[cur][i][j] = dp[i][j]; R[cur][i][j] = dp[i][j]; for (int k = 1; k < j; ++k) Min(R[cur][i][k], j - k + dp[i][j]); for (int k = j + 1; k <= m; ++k) Min(L[cur][i][k], k - j + dp[i][j]); } if (mp[i][j] == K) { X = i; Y = j; } } for (int i = 2; i <= K; ++i) { cur ^= 1; if (i > 2) { for (int j = 0; j < P[i - 2].size(); ++j) { node tmp = P[i - 2][j]; int x = tmp.x; for (int k = 1; k <= m; ++k) { L[cur][x][k] = -1; R[cur][x][k] = -1; } } } for (int j = 0; j < P[i].size(); ++j) { node tmp = P[i][j]; int x = tmp.x, y = tmp.y; for (int k = 1; k <= x; ++k) { if (L[cur ^ 1][k][y] == -1 && R[cur ^ 1][k][y] == -1) continue; Min(dp[x][y], x - k + MIN(L[cur ^ 1][k][y], R[cur ^ 1][k][y])); } for (int k = x + 1; k <= n; ++k) { if (L[cur ^ 1][k][y] == -1 && R[cur ^ 1][k][y] == -1) continue; Min(dp[x][y], k - x + MIN(L[cur ^ 1][k][y], R[cur ^ 1][k][y])); } for (int k = 1; k <= y; ++k) Min(R[cur][x][k], y - k + dp[x][y]); for (int k = y + 1; k <= m; ++k) Min(L[cur][x][k], k - y + dp[x][y]); } } printf("%d", dp[X][Y]); 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; struct node { int x, y; }; vector<node> P[305 * 305]; int n, m, K, X, Y, mp[305][305], dp[305][305], L[2][305][305], R[2][305][305]; void Min(int &a, int b) { if (a == -1 || a > b) a = b; } int MIN(int a, int b) { if (a == -1) return b; if (b == -1) return a; return min(a, b); } int main() { scanf("%d%d%d", &n, &m, &K); int cur = 0; memset(dp, -1, sizeof(dp)); memset(L[cur], -1, sizeof(L[cur])); memset(R[cur], -1, sizeof(R[cur])); memset(L[cur ^ 1], -1, sizeof(L[cur])); memset(R[cur ^ 1], -1, sizeof(R[cur])); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) scanf("%d", &mp[i][j]); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { node tmp; tmp.x = i; tmp.y = j; P[mp[i][j]].push_back(tmp); if (mp[i][j] == 1) { dp[i][j] = i + j - 2; L[cur][i][j] = dp[i][j]; R[cur][i][j] = dp[i][j]; for (int k = 1; k < j; ++k) Min(R[cur][i][k], j - k + dp[i][j]); for (int k = j + 1; k <= m; ++k) Min(L[cur][i][k], k - j + dp[i][j]); } if (mp[i][j] == K) { X = i; Y = j; } } for (int i = 2; i <= K; ++i) { cur ^= 1; if (i > 2) { for (int j = 0; j < P[i - 2].size(); ++j) { node tmp = P[i - 2][j]; int x = tmp.x; for (int k = 1; k <= m; ++k) { L[cur][x][k] = -1; R[cur][x][k] = -1; } } } for (int j = 0; j < P[i].size(); ++j) { node tmp = P[i][j]; int x = tmp.x, y = tmp.y; for (int k = 1; k <= x; ++k) { if (L[cur ^ 1][k][y] == -1 && R[cur ^ 1][k][y] == -1) continue; Min(dp[x][y], x - k + MIN(L[cur ^ 1][k][y], R[cur ^ 1][k][y])); } for (int k = x + 1; k <= n; ++k) { if (L[cur ^ 1][k][y] == -1 && R[cur ^ 1][k][y] == -1) continue; Min(dp[x][y], k - x + MIN(L[cur ^ 1][k][y], R[cur ^ 1][k][y])); } for (int k = 1; k <= y; ++k) Min(R[cur][x][k], y - k + dp[x][y]); for (int k = y + 1; k <= m; ++k) Min(L[cur][x][k], k - y + dp[x][y]); } } printf("%d", dp[X][Y]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int oo = 0x3f3f3f3f; const double eps = 1e-9; int di[] = {1, 0, -1, 0}, dj[] = {0, 1, 0, -1}; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m, x; cin >> m >> n >> x; vector<vector<int>> a(m, vector<int>(n)); vector<vector<pair<int, int>>> b(x + 1); for (int i = (0); i < (m); i++) for (int j = (0); j < (n); j++) { cin >> a[i][j]; b[a[i][j]].emplace_back(i, j); } vector<vector<int>> d(m, vector<int>(n, oo)); for (const auto &p : b[1]) d[p.first][p.second] = p.first + p.second; for (int k = (1); k < (x); k++) { cerr << k << endl; if (int((b[k]).size()) > 1000) { vector<vector<int>> dd(m, vector<int>(n, oo)); set<pair<int, pair<int, int>>> q; for (const auto &p : b[k]) { int i, j; tie(i, j) = p; dd[i][j] = d[i][j], q.insert(make_pair(d[i][j], p)); } while (int((q).size())) { int i, j; tie(i, j) = begin(q)->second; q.erase(begin(q)); for (int t = (0); t < (4); t++) { int ni = i + di[t], nj = j + dj[t]; if (ni < 0 || ni >= m || nj < 0 || nj >= n) continue; if (dd[ni][nj] < dd[i][j] + 1) continue; q.erase(make_pair(dd[ni][nj], make_pair(ni, nj))); dd[ni][nj] = dd[i][j] + 1; q.insert(make_pair(dd[ni][nj], make_pair(ni, nj))); } } for (const auto &p : b[k + 1]) d[p.first][p.second] = dd[p.first][p.second]; } else { for (const auto &p : b[k]) { int i, j; tie(i, j) = p; for (const auto &np : b[k + 1]) { int ni, nj; tie(ni, nj) = np; d[ni][nj] = min(d[ni][nj], d[i][j] + abs(i - ni) + abs(j - nj)); } } } } int res = oo; for (const auto &p : b[x]) res = min(res, d[p.first][p.second]); cout << res << endl; }
### 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 oo = 0x3f3f3f3f; const double eps = 1e-9; int di[] = {1, 0, -1, 0}, dj[] = {0, 1, 0, -1}; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m, x; cin >> m >> n >> x; vector<vector<int>> a(m, vector<int>(n)); vector<vector<pair<int, int>>> b(x + 1); for (int i = (0); i < (m); i++) for (int j = (0); j < (n); j++) { cin >> a[i][j]; b[a[i][j]].emplace_back(i, j); } vector<vector<int>> d(m, vector<int>(n, oo)); for (const auto &p : b[1]) d[p.first][p.second] = p.first + p.second; for (int k = (1); k < (x); k++) { cerr << k << endl; if (int((b[k]).size()) > 1000) { vector<vector<int>> dd(m, vector<int>(n, oo)); set<pair<int, pair<int, int>>> q; for (const auto &p : b[k]) { int i, j; tie(i, j) = p; dd[i][j] = d[i][j], q.insert(make_pair(d[i][j], p)); } while (int((q).size())) { int i, j; tie(i, j) = begin(q)->second; q.erase(begin(q)); for (int t = (0); t < (4); t++) { int ni = i + di[t], nj = j + dj[t]; if (ni < 0 || ni >= m || nj < 0 || nj >= n) continue; if (dd[ni][nj] < dd[i][j] + 1) continue; q.erase(make_pair(dd[ni][nj], make_pair(ni, nj))); dd[ni][nj] = dd[i][j] + 1; q.insert(make_pair(dd[ni][nj], make_pair(ni, nj))); } } for (const auto &p : b[k + 1]) d[p.first][p.second] = dd[p.first][p.second]; } else { for (const auto &p : b[k]) { int i, j; tie(i, j) = p; for (const auto &np : b[k + 1]) { int ni, nj; tie(ni, nj) = np; d[ni][nj] = min(d[ni][nj], d[i][j] + abs(i - ni) + abs(j - nj)); } } } } int res = oo; for (const auto &p : b[x]) res = min(res, d[p.first][p.second]); cout << res << endl; } ```
#include <bits/stdc++.h> using namespace std; int a[305][305]; struct stu { int h, z; }; const int INF = 0x3f3f3f3f; vector<stu> b[90005]; int dp[305][305]; bool vis[305][305]; int xx[] = {1, 0, 0, -1}; int yy[] = {0, 1, -1, 0}; int n, m; void bfs(int k) { queue<stu> q; int ans[305][305]; for (int i = 0; i < 305; i++) { for (int j = 0; j < 305; j++) { ans[i][j] = INF; } } for (int i = 0; i < 305; i++) { for (int j = 0; j < 305; j++) { vis[i][j] = 0; } } for (int i = 0; i < b[k - 1].size(); i++) { stu jl; jl.h = b[k - 1][i].h; jl.z = b[k - 1][i].z; q.push(jl); ans[jl.h][jl.z] = dp[jl.h][jl.z]; } while (!q.empty()) { stu jjj; jjj = q.front(); q.pop(); int jh; int jz; for (int i = 0; i < 4; i++) { jh = jjj.h + xx[i]; jz = jjj.z + yy[i]; if (jh >= 1 && jh <= n && jz >= 1 && jz <= m) { stu mm; mm.h = jh; mm.z = jz; if (ans[jh][jz] > ans[jjj.h][jjj.z] + 1) { ans[jh][jz] = ans[jjj.h][jjj.z] + 1; q.push(mm); } } } } for (int i = 0; i < b[k].size(); i++) { int ph = b[k][i].h; int pz = b[k][i].z; dp[ph][pz] = min(dp[ph][pz], ans[ph][pz]); } return; } 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", &a[i][j]); stu kkk; kkk.h = i; ; kkk.z = j; b[a[i][j]].push_back(kkk); } } for (int i = 0; i < 305; i++) { for (int j = 0; j < 305; j++) { dp[i][j] = INF; } } for (int i = 0; i < b[1].size(); i++) { dp[b[1][i].h][b[1][i].z] = b[1][i].h + b[1][i].z - 2; } for (int i = 2; i <= p; i++) { if (b[i - 1].size() * b[i].size() <= n * m) { int cnt1 = b[i - 1].size(); int cnt2 = b[i].size(); for (int p = 0; p < cnt1; p++) { for (int j = 0; j < cnt2; j++) { int ph = b[i - 1][p].h; int pz = b[i - 1][p].z; int kh = b[i][j].h; int kz = b[i][j].z; dp[kh][kz] = min(dp[kh][kz], dp[ph][pz] + abs(ph - kh) + abs(pz - kz)); } } } else { bfs(i); } } printf("%d", dp[b[p][0].h][b[p][0].z]); }
### 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 a[305][305]; struct stu { int h, z; }; const int INF = 0x3f3f3f3f; vector<stu> b[90005]; int dp[305][305]; bool vis[305][305]; int xx[] = {1, 0, 0, -1}; int yy[] = {0, 1, -1, 0}; int n, m; void bfs(int k) { queue<stu> q; int ans[305][305]; for (int i = 0; i < 305; i++) { for (int j = 0; j < 305; j++) { ans[i][j] = INF; } } for (int i = 0; i < 305; i++) { for (int j = 0; j < 305; j++) { vis[i][j] = 0; } } for (int i = 0; i < b[k - 1].size(); i++) { stu jl; jl.h = b[k - 1][i].h; jl.z = b[k - 1][i].z; q.push(jl); ans[jl.h][jl.z] = dp[jl.h][jl.z]; } while (!q.empty()) { stu jjj; jjj = q.front(); q.pop(); int jh; int jz; for (int i = 0; i < 4; i++) { jh = jjj.h + xx[i]; jz = jjj.z + yy[i]; if (jh >= 1 && jh <= n && jz >= 1 && jz <= m) { stu mm; mm.h = jh; mm.z = jz; if (ans[jh][jz] > ans[jjj.h][jjj.z] + 1) { ans[jh][jz] = ans[jjj.h][jjj.z] + 1; q.push(mm); } } } } for (int i = 0; i < b[k].size(); i++) { int ph = b[k][i].h; int pz = b[k][i].z; dp[ph][pz] = min(dp[ph][pz], ans[ph][pz]); } return; } 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", &a[i][j]); stu kkk; kkk.h = i; ; kkk.z = j; b[a[i][j]].push_back(kkk); } } for (int i = 0; i < 305; i++) { for (int j = 0; j < 305; j++) { dp[i][j] = INF; } } for (int i = 0; i < b[1].size(); i++) { dp[b[1][i].h][b[1][i].z] = b[1][i].h + b[1][i].z - 2; } for (int i = 2; i <= p; i++) { if (b[i - 1].size() * b[i].size() <= n * m) { int cnt1 = b[i - 1].size(); int cnt2 = b[i].size(); for (int p = 0; p < cnt1; p++) { for (int j = 0; j < cnt2; j++) { int ph = b[i - 1][p].h; int pz = b[i - 1][p].z; int kh = b[i][j].h; int kz = b[i][j].z; dp[kh][kz] = min(dp[kh][kz], dp[ph][pz] + abs(ph - kh) + abs(pz - kz)); } } } else { bfs(i); } } printf("%d", dp[b[p][0].h][b[p][0].z]); } ```
#include <bits/stdc++.h> using namespace std; struct Edge { int x, y, next; } edge[305 * 305]; int e, ft[305 * 305], cnt[305 * 305]; int N; long long inf, dp[305][305], d[305][305]; bool flag[305][305]; int r, c, p, maze[305][305]; int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0}; struct Node { int x, y; Node() {} Node(int x, int y) : x(x), y(y) {} bool operator<(const Node &other) const { return d[x][y] > d[other.x][other.y]; } } deq[305 * 305 * 2]; int head, tail, top; bool in(int x, int y) { return x >= 0 && x < r && y >= 0 && y < c; } void init() { N = r * c; inf = (long long)N * (long long)N + 1; e = 0; memset(ft, -1, sizeof(int) * (p + 2)); memset(cnt, 0, sizeof(int) * (p + 2)); } void insert_edge(int u, int x, int y) { cnt[u]++; edge[e].x = x; edge[e].y = y; edge[e].next = ft[u]; ft[u] = e++; } int main() { while (scanf("%d%d%d", &r, &c, &p) == 3) { init(); int tx, ty; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { scanf("%d", maze[i] + j); if (maze[i][j] == 1) dp[i][j] = i + j; else dp[i][j] = inf; insert_edge(maze[i][j], i, j); if (maze[i][j] == p) { tx = i; ty = j; } } } for (int i = 2; i <= p; i++) { if ((long long)cnt[i] * (long long)cnt[i - 1] > N) { head = tail = 0; for (int j = 0; j < r; j++) { for (int k = 0; k < c; k++) { if (dp[j][k] < inf && maze[j][k] == i - 1) { d[j][k] = dp[j][k]; flag[j][k] = true; deq[tail++] = Node(j, k); } else { flag[j][k] = false; d[j][k] = inf; } } } sort(deq, deq + tail); while (head != tail) { Node node = deq[head++]; if (head > N + 1) head = 0; for (int j = 0; j < 4; j++) { int xx = node.x + dx[j]; int yy = node.y + dy[j]; if (!in(xx, yy)) continue; if (d[xx][yy] > d[node.x][node.y] + 1) { d[xx][yy] = d[node.x][node.y] + 1; if (!flag[xx][yy]) { flag[xx][yy] = true; deq[tail++] = Node(xx, yy); if (tail > N + 1) tail = 0; } } } flag[node.x][node.y] = false; } for (int j = ft[i]; j != -1; j = edge[j].next) { dp[edge[j].x][edge[j].y] = d[edge[j].x][edge[j].y]; } } else { for (int j = ft[i]; j != -1; j = edge[j].next) { int x = edge[j].x; int y = edge[j].y; dp[x][y] = inf; for (int k = ft[i - 1]; k != -1; k = edge[k].next) { int xx = edge[k].x; int yy = edge[k].y; dp[x][y] = min(dp[x][y], dp[xx][yy] + abs(x - xx) + abs(y - yy)); } } } } cout << dp[tx][ty] << endl; } 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; struct Edge { int x, y, next; } edge[305 * 305]; int e, ft[305 * 305], cnt[305 * 305]; int N; long long inf, dp[305][305], d[305][305]; bool flag[305][305]; int r, c, p, maze[305][305]; int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0}; struct Node { int x, y; Node() {} Node(int x, int y) : x(x), y(y) {} bool operator<(const Node &other) const { return d[x][y] > d[other.x][other.y]; } } deq[305 * 305 * 2]; int head, tail, top; bool in(int x, int y) { return x >= 0 && x < r && y >= 0 && y < c; } void init() { N = r * c; inf = (long long)N * (long long)N + 1; e = 0; memset(ft, -1, sizeof(int) * (p + 2)); memset(cnt, 0, sizeof(int) * (p + 2)); } void insert_edge(int u, int x, int y) { cnt[u]++; edge[e].x = x; edge[e].y = y; edge[e].next = ft[u]; ft[u] = e++; } int main() { while (scanf("%d%d%d", &r, &c, &p) == 3) { init(); int tx, ty; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { scanf("%d", maze[i] + j); if (maze[i][j] == 1) dp[i][j] = i + j; else dp[i][j] = inf; insert_edge(maze[i][j], i, j); if (maze[i][j] == p) { tx = i; ty = j; } } } for (int i = 2; i <= p; i++) { if ((long long)cnt[i] * (long long)cnt[i - 1] > N) { head = tail = 0; for (int j = 0; j < r; j++) { for (int k = 0; k < c; k++) { if (dp[j][k] < inf && maze[j][k] == i - 1) { d[j][k] = dp[j][k]; flag[j][k] = true; deq[tail++] = Node(j, k); } else { flag[j][k] = false; d[j][k] = inf; } } } sort(deq, deq + tail); while (head != tail) { Node node = deq[head++]; if (head > N + 1) head = 0; for (int j = 0; j < 4; j++) { int xx = node.x + dx[j]; int yy = node.y + dy[j]; if (!in(xx, yy)) continue; if (d[xx][yy] > d[node.x][node.y] + 1) { d[xx][yy] = d[node.x][node.y] + 1; if (!flag[xx][yy]) { flag[xx][yy] = true; deq[tail++] = Node(xx, yy); if (tail > N + 1) tail = 0; } } } flag[node.x][node.y] = false; } for (int j = ft[i]; j != -1; j = edge[j].next) { dp[edge[j].x][edge[j].y] = d[edge[j].x][edge[j].y]; } } else { for (int j = ft[i]; j != -1; j = edge[j].next) { int x = edge[j].x; int y = edge[j].y; dp[x][y] = inf; for (int k = ft[i - 1]; k != -1; k = edge[k].next) { int xx = edge[k].x; int yy = edge[k].y; dp[x][y] = min(dp[x][y], dp[xx][yy] + abs(x - xx) + abs(y - yy)); } } } } cout << dp[tx][ty] << endl; } return 0; } ```
#include <bits/stdc++.h> using namespace std; int ma[305][305]; struct node { int x; int y; int id; int cost; bool operator<(const node& cx) const { return cost > cx.cost; } }; vector<node> vec[100000]; bool flag[305][305]; int minn[305][305]; int mim[305][305]; priority_queue<node> que; int n, m; void bfs(); int xx[4] = {0, 0, -1, 1}; int yy[4] = {1, -1, 0, 0}; int main(void) { int k; while (scanf("%d %d %d", &n, &m, &k) != EOF) { int i, j; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { scanf("%d", &ma[i][j]); } } memset(flag, 0, sizeof(flag)); for (i = 0; i < 305; i++) { for (j = 0; j < 305; j++) { minn[i][j] = 1e9; } } while (!que.empty()) que.pop(); for (i = 0; i < 1000; i++) vec[i].clear(); int s = 0; int ix, iy; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { node ab; ab.id = ma[i][j]; if (ab.id == k) ix = i, iy = j; ab.x = i; ab.y = j; vec[ab.id].push_back(ab); } } for (i = 0; i < vec[1].size(); i++) { node ac = vec[1][i]; minn[ac.x][ac.y] = abs(ac.x - 1) + abs(ac.y - 1); } node ab; for (i = 2; i <= k; i++) { int s1 = vec[i].size(); int s2 = vec[i - 1].size(); if (s1 * s2 <= 7 * n * m) { for (s = 0; s < s1; s++) { for (j = 0; j < s2; j++) { node a = vec[i][s]; node b = vec[i - 1][j]; minn[a.x][a.y] = min(minn[a.x][a.y], minn[b.x][b.y] + abs(a.x - b.x) + abs(a.y - b.y)); } } } else { while (!que.empty()) que.pop(); for (s = 1; s <= n; s++) { for (j = 1; j <= m; j++) { mim[s][j] = 1e9; } } for (s = 0; s < vec[i - 1].size(); s++) { node ac = vec[i - 1][s]; ac.cost = minn[ac.x][ac.y]; mim[ac.x][ac.y] = minn[ac.x][ac.y]; que.push(ac); } bfs(); for (s = 0; s < vec[i].size(); s++) { node ac = vec[i][s]; minn[ac.x][ac.y] = mim[ac.x][ac.y]; } } } printf("%d\n", minn[ix][iy]); } return 0; } void bfs() { while (!que.empty()) { node ac = que.top(); que.pop(); for (int i = 0; i < 4; i++) { int nx = ac.x + xx[i]; int ny = ac.y + yy[i]; if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && mim[nx][ny] > mim[ac.x][ac.y] + 1) { mim[nx][ny] = mim[ac.x][ac.y] + 1; node acc; acc.x = nx; acc.y = ny; acc.cost = mim[nx][ny]; que.push(acc); } } } }
### 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 ma[305][305]; struct node { int x; int y; int id; int cost; bool operator<(const node& cx) const { return cost > cx.cost; } }; vector<node> vec[100000]; bool flag[305][305]; int minn[305][305]; int mim[305][305]; priority_queue<node> que; int n, m; void bfs(); int xx[4] = {0, 0, -1, 1}; int yy[4] = {1, -1, 0, 0}; int main(void) { int k; while (scanf("%d %d %d", &n, &m, &k) != EOF) { int i, j; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { scanf("%d", &ma[i][j]); } } memset(flag, 0, sizeof(flag)); for (i = 0; i < 305; i++) { for (j = 0; j < 305; j++) { minn[i][j] = 1e9; } } while (!que.empty()) que.pop(); for (i = 0; i < 1000; i++) vec[i].clear(); int s = 0; int ix, iy; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { node ab; ab.id = ma[i][j]; if (ab.id == k) ix = i, iy = j; ab.x = i; ab.y = j; vec[ab.id].push_back(ab); } } for (i = 0; i < vec[1].size(); i++) { node ac = vec[1][i]; minn[ac.x][ac.y] = abs(ac.x - 1) + abs(ac.y - 1); } node ab; for (i = 2; i <= k; i++) { int s1 = vec[i].size(); int s2 = vec[i - 1].size(); if (s1 * s2 <= 7 * n * m) { for (s = 0; s < s1; s++) { for (j = 0; j < s2; j++) { node a = vec[i][s]; node b = vec[i - 1][j]; minn[a.x][a.y] = min(minn[a.x][a.y], minn[b.x][b.y] + abs(a.x - b.x) + abs(a.y - b.y)); } } } else { while (!que.empty()) que.pop(); for (s = 1; s <= n; s++) { for (j = 1; j <= m; j++) { mim[s][j] = 1e9; } } for (s = 0; s < vec[i - 1].size(); s++) { node ac = vec[i - 1][s]; ac.cost = minn[ac.x][ac.y]; mim[ac.x][ac.y] = minn[ac.x][ac.y]; que.push(ac); } bfs(); for (s = 0; s < vec[i].size(); s++) { node ac = vec[i][s]; minn[ac.x][ac.y] = mim[ac.x][ac.y]; } } } printf("%d\n", minn[ix][iy]); } return 0; } void bfs() { while (!que.empty()) { node ac = que.top(); que.pop(); for (int i = 0; i < 4; i++) { int nx = ac.x + xx[i]; int ny = ac.y + yy[i]; if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && mim[nx][ny] > mim[ac.x][ac.y] + 1) { mim[nx][ny] = mim[ac.x][ac.y] + 1; node acc; acc.x = nx; acc.y = ny; acc.cost = mim[nx][ny]; que.push(acc); } } } } ```
#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() { ios_base::sync_with_stdio(false); 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 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 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() { ios_base::sync_with_stdio(false); 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 = 3e2, magic = 1e5; int n, m, p, mt[N + 2][N + 2], ds[N + 2][N + 2], tmp[N + 2][N + 2], qd[N + 2][N + 2]; vector<pair<int, int> > po[N * N + 2]; void goNext(int tr) { if (po[tr].size() * po[tr - 1].size() <= magic) { for (auto x : po[tr - 1]) { ds[x.first][x.second] = 1e9; for (auto y : po[tr]) ds[x.first][x.second] = min(ds[x.first][x.second], ds[y.first][y.second] + abs(x.first - y.first) + abs(x.second - y.second)); } return; } queue<pair<int, int> > q; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { tmp[i][j] = 1e9; qd[i][j] = 0; if (mt[i][j] == tr) { tmp[i][j] = ds[i][j]; q.push({i, j}); qd[i][j] = 1; } } } auto isV = [](int i, int j) { if (i < 1 || i > n || j < 1 || j > m) return false; return true; }; while ((int)q.size()) { pair<int, int> p = q.front(); q.pop(); int u = p.first, v = p.second; qd[u][v] = 0; if (isV(u + 1, v) && tmp[u][v] + 1 < tmp[u + 1][v]) { tmp[u + 1][v] = tmp[u][v] + 1; if (qd[u + 1][v] == 0) q.push({u + 1, v}), qd[u + 1][v] = 1; } if (isV(u - 1, v) && tmp[u][v] + 1 < tmp[u - 1][v]) { tmp[u - 1][v] = tmp[u][v] + 1; if (qd[u - 1][v] == 0) q.push({u - 1, v}), qd[u - 1][v] = 1; } if (isV(u, v + 1) && tmp[u][v] + 1 < tmp[u][v + 1]) { tmp[u][v + 1] = tmp[u][v] + 1; if (qd[u][v + 1] == 0) q.push({u, v + 1}), qd[u][v + 1] = 1; } if (isV(u, v - 1) && tmp[u][v] + 1 < tmp[u][v - 1]) { tmp[u][v - 1] = tmp[u][v] + 1; if (qd[u][v - 1] == 0) q.push({u, v - 1}), qd[u][v - 1] = 1; } } for (auto x : po[tr - 1]) ds[x.first][x.second] = tmp[x.first][x.second]; } 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 >> mt[i][j]; po[mt[i][j]].push_back({i, j}); } } for (int i = p; i > 1; i--) goNext(i); int ans = 1e9; for (auto x : po[1]) ans = min(ans, ds[x.first][x.second] + x.first + x.second - 2); cout << ans << endl; 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 N = 3e2, magic = 1e5; int n, m, p, mt[N + 2][N + 2], ds[N + 2][N + 2], tmp[N + 2][N + 2], qd[N + 2][N + 2]; vector<pair<int, int> > po[N * N + 2]; void goNext(int tr) { if (po[tr].size() * po[tr - 1].size() <= magic) { for (auto x : po[tr - 1]) { ds[x.first][x.second] = 1e9; for (auto y : po[tr]) ds[x.first][x.second] = min(ds[x.first][x.second], ds[y.first][y.second] + abs(x.first - y.first) + abs(x.second - y.second)); } return; } queue<pair<int, int> > q; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { tmp[i][j] = 1e9; qd[i][j] = 0; if (mt[i][j] == tr) { tmp[i][j] = ds[i][j]; q.push({i, j}); qd[i][j] = 1; } } } auto isV = [](int i, int j) { if (i < 1 || i > n || j < 1 || j > m) return false; return true; }; while ((int)q.size()) { pair<int, int> p = q.front(); q.pop(); int u = p.first, v = p.second; qd[u][v] = 0; if (isV(u + 1, v) && tmp[u][v] + 1 < tmp[u + 1][v]) { tmp[u + 1][v] = tmp[u][v] + 1; if (qd[u + 1][v] == 0) q.push({u + 1, v}), qd[u + 1][v] = 1; } if (isV(u - 1, v) && tmp[u][v] + 1 < tmp[u - 1][v]) { tmp[u - 1][v] = tmp[u][v] + 1; if (qd[u - 1][v] == 0) q.push({u - 1, v}), qd[u - 1][v] = 1; } if (isV(u, v + 1) && tmp[u][v] + 1 < tmp[u][v + 1]) { tmp[u][v + 1] = tmp[u][v] + 1; if (qd[u][v + 1] == 0) q.push({u, v + 1}), qd[u][v + 1] = 1; } if (isV(u, v - 1) && tmp[u][v] + 1 < tmp[u][v - 1]) { tmp[u][v - 1] = tmp[u][v] + 1; if (qd[u][v - 1] == 0) q.push({u, v - 1}), qd[u][v - 1] = 1; } } for (auto x : po[tr - 1]) ds[x.first][x.second] = tmp[x.first][x.second]; } 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 >> mt[i][j]; po[mt[i][j]].push_back({i, j}); } } for (int i = p; i > 1; i--) goNext(i); int ans = 1e9; for (auto x : po[1]) ans = min(ans, ds[x.first][x.second] + x.first + x.second - 2); cout << ans << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; long long dx[] = {1, 0, 0, -1}; long long dy[] = {0, -1, 1, 0}; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long n, m, p; cin >> n >> m >> p; vector<pair<long long, long long> > a[p + 1]; for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { long long x; cin >> x; a[x].push_back({i, j}); } } long long dp[n][m], dist[n][m]; for (auto &ele : a[1]) dp[ele.first][ele.second] = ele.first + ele.second; for (long long i = 2; i <= p; i++) { if (1ll * a[i].size() * a[i - 1].size() <= (n * m)) { for (auto &ele : a[i]) { long long x = ele.first, y = ele.second; dp[x][y] = 1e16; for (auto &node : a[i - 1]) { long long px = node.first, py = node.second; long long dist = abs(px - x) + abs(py - y); if (dp[px][py] + dist < dp[x][y]) dp[x][y] = dp[px][py] + dist; } } } else { memset(dist, -1, sizeof(dist)); set<pair<long long, pair<long long, long long> > > st; for (auto &ele : a[i - 1]) st.insert({dp[ele.first][ele.second], {ele.first, ele.second}}); auto node = *(st.begin()); st.erase(st.begin()); queue<pair<long long, long long> > q; q.push(node.second); dist[node.second.first][node.second.second] = node.first; while (!q.empty()) { auto cur = q.front(); q.pop(); long long cur_dist = dist[cur.first][cur.second]; while (!st.empty() && st.begin()->first <= cur_dist + 1) { auto node = *(st.begin()); st.erase(node); q.push(node.second); dist[node.second.first][node.second.second] = node.first; } for (long long j = 0; j < 4; j++) { long long nx = cur.first + dx[j]; long long ny = cur.second + dy[j]; if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; if (dist[nx][ny] == -1) dist[nx][ny] = cur_dist + 1, q.push({nx, ny}); } } for (auto &ele : a[i]) dp[ele.first][ele.second] = dist[ele.first][ele.second]; } } long long x = a[p][0].first, y = a[p][0].second; cout << dp[x][y]; }
### 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; long long dx[] = {1, 0, 0, -1}; long long dy[] = {0, -1, 1, 0}; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long n, m, p; cin >> n >> m >> p; vector<pair<long long, long long> > a[p + 1]; for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { long long x; cin >> x; a[x].push_back({i, j}); } } long long dp[n][m], dist[n][m]; for (auto &ele : a[1]) dp[ele.first][ele.second] = ele.first + ele.second; for (long long i = 2; i <= p; i++) { if (1ll * a[i].size() * a[i - 1].size() <= (n * m)) { for (auto &ele : a[i]) { long long x = ele.first, y = ele.second; dp[x][y] = 1e16; for (auto &node : a[i - 1]) { long long px = node.first, py = node.second; long long dist = abs(px - x) + abs(py - y); if (dp[px][py] + dist < dp[x][y]) dp[x][y] = dp[px][py] + dist; } } } else { memset(dist, -1, sizeof(dist)); set<pair<long long, pair<long long, long long> > > st; for (auto &ele : a[i - 1]) st.insert({dp[ele.first][ele.second], {ele.first, ele.second}}); auto node = *(st.begin()); st.erase(st.begin()); queue<pair<long long, long long> > q; q.push(node.second); dist[node.second.first][node.second.second] = node.first; while (!q.empty()) { auto cur = q.front(); q.pop(); long long cur_dist = dist[cur.first][cur.second]; while (!st.empty() && st.begin()->first <= cur_dist + 1) { auto node = *(st.begin()); st.erase(node); q.push(node.second); dist[node.second.first][node.second.second] = node.first; } for (long long j = 0; j < 4; j++) { long long nx = cur.first + dx[j]; long long ny = cur.second + dy[j]; if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; if (dist[nx][ny] == -1) dist[nx][ny] = cur_dist + 1, q.push({nx, ny}); } } for (auto &ele : a[i]) dp[ele.first][ele.second] = dist[ele.first][ele.second]; } } long long x = a[p][0].first, y = a[p][0].second; cout << dp[x][y]; } ```
#include <bits/stdc++.h> using namespace std; const long long N = 305; const long long INF = 1e9 + 5; const long long mod = 1e9 + 7; long long n, m, t, a[N][N]; vector<pair<long long, long long>> pos[N * N]; pair<long long, long long> loc; long long adjx[4] = {-1, 0, 1, 0}, adjy[4] = {0, 1, 0, -1}; bool inRange(long long x, long long y) { return x >= 1 && x <= n && y >= 1 && y <= m; } long long calc(long long x, long long y, long long z, long long w) { return abs(x - z) + abs(y - w); } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> t; vector<vector<long long>> dp(n + 1, vector<long long>(m + 1, INF)); for (long long i = 1; i <= n; i++) { for (long long j = 1; j <= m; j++) { cin >> a[i][j]; pos[a[i][j]].push_back({i, j}); if (a[i][j] == t) loc = {i, j}; if (a[i][j] == 1) dp[i][j] = i + j - 2; } } vector<vector<long long>> dist; vector<array<long long, 3>> q; vector<array<long long, 3>> s; for (long long i = 2; i <= t; i++) { if (pos[i - 1].size() * pos[i].size() > n * m) { s.clear(); q.clear(); dist = vector<vector<long long>>(n + 1, vector<long long>(m + 1, -1)); for (auto [x, y] : pos[i - 1]) { s.push_back({dp[x][y], x, y}); } sort(s.begin(), s.end()); q.push_back(s[0]); long long idx = 1, j = 0; dist[s[0][1]][s[0][2]] = s[0][0]; while (j < q.size()) { auto [z, x1, y1] = q[j]; j++; while (idx < s.size() && s[idx][0] <= z) q.push_back(s[idx++]); for (long long k = 0; k < 4; k++) { long long x2 = x1 + adjx[k], y2 = y1 + adjy[k]; if (inRange(x2, y2) && dist[x2][y2] == -1) { dist[x2][y2] = z + 1; q.push_back({z + 1, x2, y2}); } } } for (auto [x, y] : pos[i]) dp[x][y] = dist[x][y]; } else { for (auto [x1, y1] : pos[i]) { for (auto [x2, y2] : pos[i - 1]) dp[x1][y1] = min(dp[x1][y1], dp[x2][y2] + calc(x1, y1, x2, y2)); } } } cout << dp[loc.first][loc.second] << "\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 long long N = 305; const long long INF = 1e9 + 5; const long long mod = 1e9 + 7; long long n, m, t, a[N][N]; vector<pair<long long, long long>> pos[N * N]; pair<long long, long long> loc; long long adjx[4] = {-1, 0, 1, 0}, adjy[4] = {0, 1, 0, -1}; bool inRange(long long x, long long y) { return x >= 1 && x <= n && y >= 1 && y <= m; } long long calc(long long x, long long y, long long z, long long w) { return abs(x - z) + abs(y - w); } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> t; vector<vector<long long>> dp(n + 1, vector<long long>(m + 1, INF)); for (long long i = 1; i <= n; i++) { for (long long j = 1; j <= m; j++) { cin >> a[i][j]; pos[a[i][j]].push_back({i, j}); if (a[i][j] == t) loc = {i, j}; if (a[i][j] == 1) dp[i][j] = i + j - 2; } } vector<vector<long long>> dist; vector<array<long long, 3>> q; vector<array<long long, 3>> s; for (long long i = 2; i <= t; i++) { if (pos[i - 1].size() * pos[i].size() > n * m) { s.clear(); q.clear(); dist = vector<vector<long long>>(n + 1, vector<long long>(m + 1, -1)); for (auto [x, y] : pos[i - 1]) { s.push_back({dp[x][y], x, y}); } sort(s.begin(), s.end()); q.push_back(s[0]); long long idx = 1, j = 0; dist[s[0][1]][s[0][2]] = s[0][0]; while (j < q.size()) { auto [z, x1, y1] = q[j]; j++; while (idx < s.size() && s[idx][0] <= z) q.push_back(s[idx++]); for (long long k = 0; k < 4; k++) { long long x2 = x1 + adjx[k], y2 = y1 + adjy[k]; if (inRange(x2, y2) && dist[x2][y2] == -1) { dist[x2][y2] = z + 1; q.push_back({z + 1, x2, y2}); } } } for (auto [x, y] : pos[i]) dp[x][y] = dist[x][y]; } else { for (auto [x1, y1] : pos[i]) { for (auto [x2, y2] : pos[i - 1]) dp[x1][y1] = min(dp[x1][y1], dp[x2][y2] + calc(x1, y1, x2, y2)); } } } cout << dp[loc.first][loc.second] << "\n"; } ```
#include <bits/stdc++.h> using namespace std; inline long long sqr(long long x) { return x * x; } int tree[4][1505][1505], dp[305][305]; int n, m, p, id; vector<pair<int, int> > g[90005]; void update_y(int kx, int lx, int rx, int ky, int l, int r, int x, int y, int val) { if (l == r) { if (lx == rx) tree[id][kx][ky] = val; else tree[id][kx][ky] = min(tree[id][kx * 2][ky], tree[id][kx * 2 + 1][ky]); } else { int mid = (l + r) >> 1; if (y <= mid) update_y(kx, lx, rx, ky * 2, l, mid, x, y, val); else update_y(kx, lx, rx, ky * 2 + 1, mid + 1, r, x, y, val); tree[id][kx][ky] = min(tree[id][kx][ky * 2], tree[id][kx][ky * 2 + 1]); } } void update_x(int kx, int l, int r, int x, int y, int val) { if (l != r) { int mid = (l + r) >> 1; if (x <= mid) update_x(kx * 2, l, mid, x, y, val); else update_x(kx * 2 + 1, mid + 1, r, x, y, val); } update_y(kx, l, r, 1, 1, m, x, y, val); } int query_y(int kx, int ky, int l, int r, int ly, int ry) { if (ly > ry) return 2e9 + 7; if (ly == l && ry == r) return tree[id][kx][ky]; int mid = (l + r) >> 1; return min(query_y(kx, ky * 2, l, mid, ly, min(ry, mid)), query_y(kx, ky * 2 + 1, mid + 1, r, max(ly, mid + 1), ry)); } int query_x(int kx, int l, int r, int lx, int rx, int ly, int ry) { if (lx > rx) return 2e9 + 7; if (lx == l && rx == r) return query_y(kx, 1, 1, m, ly, ry); int mid = (l + r) >> 1; return min(query_x(kx * 2, l, mid, lx, min(rx, mid), ly, ry), query_x(kx * 2 + 1, mid + 1, r, max(lx, mid + 1), rx, ly, ry)); } int main() { scanf("%d%d%d", &n, &m, &p); for (int i = (1), _b = (n); i <= _b; ++i) for (int j = (1), _b = (m); j <= _b; ++j) { int x; scanf("%d", &x); g[x].push_back(pair<int, int>(i, j)); if (x == 1) dp[i][j] = i + j - 2; } for (int i = 0, _a = (4); i < _a; ++i) for (int j = (0), _b = (1500); j <= _b; ++j) for (int k = (0), _b = (1500); k <= _b; ++k) tree[i][j][k] = 2e9 + 7; for (int i = (2), _b = (p); i <= _b; ++i) { for (int j = 0, _a = (((int)g[i - 1].size())); j < _a; ++j) { int x = g[i - 1][j].first, y = g[i - 1][j].second; id = 0; update_x(1, 1, n, x, y, dp[x][y] - x - y); id = 1; update_x(1, 1, n, x, y, dp[x][y] - x + y); id = 2; update_x(1, 1, n, x, y, dp[x][y] + x - y); id = 3; update_x(1, 1, n, x, y, dp[x][y] + x + y); } for (int j = 0, _a = (((int)g[i].size())); j < _a; ++j) { int x = g[i][j].first, y = g[i][j].second; int &tmp = dp[x][y]; tmp = 2e9 + 7; id = 0; tmp = min(tmp, query_x(1, 1, n, 1, x, 1, y) + x + y); id = 1; tmp = min(tmp, query_x(1, 1, n, 1, x, y + 1, m) + x - y); id = 2; tmp = min(tmp, query_x(1, 1, n, x + 1, n, 1, y) - x + y); id = 3; tmp = min(tmp, query_x(1, 1, n, x + 1, n, y + 1, m) - x - y); } for (int j = 0, _a = (((int)g[i - 1].size())); j < _a; ++j) { int x = g[i - 1][j].first, y = g[i - 1][j].second; id = 0; update_x(1, 1, n, x, y, 2e9 + 7); id = 1; update_x(1, 1, n, x, y, 2e9 + 7); id = 2; update_x(1, 1, n, x, y, 2e9 + 7); id = 3; update_x(1, 1, n, x, y, 2e9 + 7); } } printf("%d", dp[g[p][0].first][g[p][0].second]); 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; inline long long sqr(long long x) { return x * x; } int tree[4][1505][1505], dp[305][305]; int n, m, p, id; vector<pair<int, int> > g[90005]; void update_y(int kx, int lx, int rx, int ky, int l, int r, int x, int y, int val) { if (l == r) { if (lx == rx) tree[id][kx][ky] = val; else tree[id][kx][ky] = min(tree[id][kx * 2][ky], tree[id][kx * 2 + 1][ky]); } else { int mid = (l + r) >> 1; if (y <= mid) update_y(kx, lx, rx, ky * 2, l, mid, x, y, val); else update_y(kx, lx, rx, ky * 2 + 1, mid + 1, r, x, y, val); tree[id][kx][ky] = min(tree[id][kx][ky * 2], tree[id][kx][ky * 2 + 1]); } } void update_x(int kx, int l, int r, int x, int y, int val) { if (l != r) { int mid = (l + r) >> 1; if (x <= mid) update_x(kx * 2, l, mid, x, y, val); else update_x(kx * 2 + 1, mid + 1, r, x, y, val); } update_y(kx, l, r, 1, 1, m, x, y, val); } int query_y(int kx, int ky, int l, int r, int ly, int ry) { if (ly > ry) return 2e9 + 7; if (ly == l && ry == r) return tree[id][kx][ky]; int mid = (l + r) >> 1; return min(query_y(kx, ky * 2, l, mid, ly, min(ry, mid)), query_y(kx, ky * 2 + 1, mid + 1, r, max(ly, mid + 1), ry)); } int query_x(int kx, int l, int r, int lx, int rx, int ly, int ry) { if (lx > rx) return 2e9 + 7; if (lx == l && rx == r) return query_y(kx, 1, 1, m, ly, ry); int mid = (l + r) >> 1; return min(query_x(kx * 2, l, mid, lx, min(rx, mid), ly, ry), query_x(kx * 2 + 1, mid + 1, r, max(lx, mid + 1), rx, ly, ry)); } int main() { scanf("%d%d%d", &n, &m, &p); for (int i = (1), _b = (n); i <= _b; ++i) for (int j = (1), _b = (m); j <= _b; ++j) { int x; scanf("%d", &x); g[x].push_back(pair<int, int>(i, j)); if (x == 1) dp[i][j] = i + j - 2; } for (int i = 0, _a = (4); i < _a; ++i) for (int j = (0), _b = (1500); j <= _b; ++j) for (int k = (0), _b = (1500); k <= _b; ++k) tree[i][j][k] = 2e9 + 7; for (int i = (2), _b = (p); i <= _b; ++i) { for (int j = 0, _a = (((int)g[i - 1].size())); j < _a; ++j) { int x = g[i - 1][j].first, y = g[i - 1][j].second; id = 0; update_x(1, 1, n, x, y, dp[x][y] - x - y); id = 1; update_x(1, 1, n, x, y, dp[x][y] - x + y); id = 2; update_x(1, 1, n, x, y, dp[x][y] + x - y); id = 3; update_x(1, 1, n, x, y, dp[x][y] + x + y); } for (int j = 0, _a = (((int)g[i].size())); j < _a; ++j) { int x = g[i][j].first, y = g[i][j].second; int &tmp = dp[x][y]; tmp = 2e9 + 7; id = 0; tmp = min(tmp, query_x(1, 1, n, 1, x, 1, y) + x + y); id = 1; tmp = min(tmp, query_x(1, 1, n, 1, x, y + 1, m) + x - y); id = 2; tmp = min(tmp, query_x(1, 1, n, x + 1, n, 1, y) - x + y); id = 3; tmp = min(tmp, query_x(1, 1, n, x + 1, n, y + 1, m) - x - y); } for (int j = 0, _a = (((int)g[i - 1].size())); j < _a; ++j) { int x = g[i - 1][j].first, y = g[i - 1][j].second; id = 0; update_x(1, 1, n, x, y, 2e9 + 7); id = 1; update_x(1, 1, n, x, y, 2e9 + 7); id = 2; update_x(1, 1, n, x, y, 2e9 + 7); id = 3; update_x(1, 1, n, x, y, 2e9 + 7); } } printf("%d", dp[g[p][0].first][g[p][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; template <class T> inline T bigmod(T p, T e, T M) { long long int ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); } template <class T> inline T modinverse(T a, T M) { return bigmod(a, M - 2, M); } template <class T> inline T bpow(T p, T e) { long long int ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p); p = (p * p); } return (T)ret; } int toInt(string s) { int sm; stringstream ss(s); ss >> sm; return sm; } int toLlint(string s) { long long int sm; stringstream ss(s); ss >> sm; return sm; } int ts, kk = 1; int p[301][301]; bool vs[301][301]; int n, m, x, gr[301][301]; int ds[301][301]; vector<pair<int, int> > v[301 * 301]; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; int main() { int t, i, j, k; pair<int, int> q; scanf("%d%d%d", &n, &m, &x); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { scanf("%d", &gr[i][j]); v[gr[i][j]].push_back(pair<int, int>(i, j)); if (gr[i][j] == 1) p[i][j] = i + j; else p[i][j] = 1000000007LL; } } for (t = 2; t <= x; t++) { if (v[t - 1].size() * v[t].size() > n * m) { memset(ds, -1, sizeof(ds)); queue<int> qu; for (i = 0; i < v[t - 1].size(); i++) { qu.push(v[t - 1][i].first); qu.push(v[t - 1][i].second); ds[v[t - 1][i].first][v[t - 1][i].second] = p[v[t - 1][i].first][v[t - 1][i].second]; } while (!qu.empty()) { int u = qu.front(); qu.pop(); int v = qu.front(); qu.pop(); for (k = 0; k < 4; k++) { int nu = u + dx[k]; int nv = v + dy[k]; if (nu >= 0 && nu < n && nv >= 0 && nv < m && (ds[nu][nv] == -1 || ds[nu][nv] > ds[u][v] + 1)) { ds[nu][nv] = ds[u][v] + 1; qu.push(nu); qu.push(nv); if (gr[nu][nv] == t) p[nu][nv] = ds[nu][nv]; } } } } else { for (i = 0; i < v[t - 1].size(); i++) for (j = 0; j < v[t].size(); j++) { p[v[t][j].first][v[t][j].second] = min(p[v[t][j].first][v[t][j].second], p[v[t - 1][i].first][v[t - 1][i].second] + abs(v[t - 1][i].first - v[t][j].first) + abs(v[t - 1][i].second - v[t][j].second)); } } } printf("%d\n", p[v[x][0].first][v[x][0].second]); 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; template <class T> inline T bigmod(T p, T e, T M) { long long int ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); } template <class T> inline T modinverse(T a, T M) { return bigmod(a, M - 2, M); } template <class T> inline T bpow(T p, T e) { long long int ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p); p = (p * p); } return (T)ret; } int toInt(string s) { int sm; stringstream ss(s); ss >> sm; return sm; } int toLlint(string s) { long long int sm; stringstream ss(s); ss >> sm; return sm; } int ts, kk = 1; int p[301][301]; bool vs[301][301]; int n, m, x, gr[301][301]; int ds[301][301]; vector<pair<int, int> > v[301 * 301]; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; int main() { int t, i, j, k; pair<int, int> q; scanf("%d%d%d", &n, &m, &x); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { scanf("%d", &gr[i][j]); v[gr[i][j]].push_back(pair<int, int>(i, j)); if (gr[i][j] == 1) p[i][j] = i + j; else p[i][j] = 1000000007LL; } } for (t = 2; t <= x; t++) { if (v[t - 1].size() * v[t].size() > n * m) { memset(ds, -1, sizeof(ds)); queue<int> qu; for (i = 0; i < v[t - 1].size(); i++) { qu.push(v[t - 1][i].first); qu.push(v[t - 1][i].second); ds[v[t - 1][i].first][v[t - 1][i].second] = p[v[t - 1][i].first][v[t - 1][i].second]; } while (!qu.empty()) { int u = qu.front(); qu.pop(); int v = qu.front(); qu.pop(); for (k = 0; k < 4; k++) { int nu = u + dx[k]; int nv = v + dy[k]; if (nu >= 0 && nu < n && nv >= 0 && nv < m && (ds[nu][nv] == -1 || ds[nu][nv] > ds[u][v] + 1)) { ds[nu][nv] = ds[u][v] + 1; qu.push(nu); qu.push(nv); if (gr[nu][nv] == t) p[nu][nv] = ds[nu][nv]; } } } } else { for (i = 0; i < v[t - 1].size(); i++) for (j = 0; j < v[t].size(); j++) { p[v[t][j].first][v[t][j].second] = min(p[v[t][j].first][v[t][j].second], p[v[t - 1][i].first][v[t - 1][i].second] + abs(v[t - 1][i].first - v[t][j].first) + abs(v[t - 1][i].second - v[t][j].second)); } } } printf("%d\n", p[v[x][0].first][v[x][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const long long inf = ~0ull >> 4; vector<pair<int, int> > key[90005]; long long ans[405][405]; long long dis[405][405]; int vis[405][405]; int main() { int n, m, p, x; scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &x); key[x].push_back(pair<int, int>(i, j)); ans[i][j] = inf; dis[i][j] = inf; } } for (int i = 1; i <= m; ++i) { vis[1][i] = 0; dis[1][i] = i - 1; } for (int i = 1; i <= p; ++i) { for (auto& j : key[i]) { for (int k = 1; k <= n; ++k) { if (vis[k][j.second] == i - 1) ans[j.first][j.second] = min(ans[j.first][j.second], dis[k][j.second] + abs(k - j.first)); } } for (auto& j : key[i]) { for (int k = 1; k <= m; ++k) { if (vis[j.first][k] != i) dis[j.first][k] = inf; dis[j.first][k] = min(dis[j.first][k], ans[j.first][j.second] + abs(k - j.second)); vis[j.first][k] = i; } } } printf("%lld\n", ans[key[p][0].first][key[p][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; const long long inf = ~0ull >> 4; vector<pair<int, int> > key[90005]; long long ans[405][405]; long long dis[405][405]; int vis[405][405]; int main() { int n, m, p, x; scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &x); key[x].push_back(pair<int, int>(i, j)); ans[i][j] = inf; dis[i][j] = inf; } } for (int i = 1; i <= m; ++i) { vis[1][i] = 0; dis[1][i] = i - 1; } for (int i = 1; i <= p; ++i) { for (auto& j : key[i]) { for (int k = 1; k <= n; ++k) { if (vis[k][j.second] == i - 1) ans[j.first][j.second] = min(ans[j.first][j.second], dis[k][j.second] + abs(k - j.first)); } } for (auto& j : key[i]) { for (int k = 1; k <= m; ++k) { if (vis[j.first][k] != i) dis[j.first][k] = inf; dis[j.first][k] = min(dis[j.first][k], ans[j.first][j.second] + abs(k - j.second)); vis[j.first][k] = i; } } } printf("%lld\n", ans[key[p][0].first][key[p][0].second]); } ```
#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 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 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> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; vector<int> a[300 * 300 + 5]; int ans[300 * 300 + 5]; int dis[300 * 300 + 5]; int vis[300 * 300 + 5]; int main() { int n, m, p, x; cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &x); a[x].push_back(i * m + j); } } memset((dis), (0x3f), sizeof((dis))); memset((ans), (0x3f), sizeof((ans))); for (int i = 0; i < m; i++) { dis[i] = i; vis[i] = 0; } for (int i = 1; i <= p; i++) { for (auto now : a[i]) { int a2 = now / m, b2 = now % m; for (int j = 0; j < n; j++) { int pre = j * m + b2; if (vis[pre] == i - 1) { ans[now] = min(ans[now], dis[pre] + abs(j - a2)); } } } for (auto now : a[i]) { int a2 = now / m, b2 = now % m; ; for (int j = 0; j < m; j++) { int ne = a2 * m + j; if (vis[ne] != i) { vis[ne] = i; dis[ne] = ans[now] + abs(b2 - j); } else { dis[ne] = min(dis[ne], ans[now] + abs(b2 - j)); } } } } cout << ans[a[p][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> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; vector<int> a[300 * 300 + 5]; int ans[300 * 300 + 5]; int dis[300 * 300 + 5]; int vis[300 * 300 + 5]; int main() { int n, m, p, x; cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &x); a[x].push_back(i * m + j); } } memset((dis), (0x3f), sizeof((dis))); memset((ans), (0x3f), sizeof((ans))); for (int i = 0; i < m; i++) { dis[i] = i; vis[i] = 0; } for (int i = 1; i <= p; i++) { for (auto now : a[i]) { int a2 = now / m, b2 = now % m; for (int j = 0; j < n; j++) { int pre = j * m + b2; if (vis[pre] == i - 1) { ans[now] = min(ans[now], dis[pre] + abs(j - a2)); } } } for (auto now : a[i]) { int a2 = now / m, b2 = now % m; ; for (int j = 0; j < m; j++) { int ne = a2 * m + j; if (vis[ne] != i) { vis[ne] = i; dis[ne] = ans[now] + abs(b2 - j); } else { dis[ne] = min(dis[ne], ans[now] + abs(b2 - j)); } } } } cout << ans[a[p][0]] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAXN = 305; struct sss { int a, b, c; bool operator<(const sss& a) const { return c < a.c; } }; vector<sss> v[MAXN * MAXN]; int cost(int a, int b, int c, int d) { return abs(a - c) + abs(b - d); } int main() { int m, n, i, j, k, p; cin >> m >> n >> p; for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) { int num; cin >> num; v[num].push_back({i, j, 999999999}); } } i = 1; for (j = 0; j < v[i].size(); j++) { v[i][j].c = cost(v[i][j].a, v[i][j].b, 1, 1); } for (i = 2; i <= p; i++) { sort((v[i - 1]).begin(), (v[i - 1]).end()); for (j = 0; j < v[i].size(); j++) { for (k = 0; k < min((int)v[i - 1].size(), m + n + 2); k++) { v[i][j].c = min(v[i][j].c, v[i - 1][k].c + cost(v[i - 1][k].a, v[i - 1][k].b, v[i][j].a, v[i][j].b)); } } } int ans = 999999999; i = p; for (j = 0; j < v[i].size(); j++) ans = min(ans, v[i][j].c); cout << ans << endl; }
### 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 = 305; struct sss { int a, b, c; bool operator<(const sss& a) const { return c < a.c; } }; vector<sss> v[MAXN * MAXN]; int cost(int a, int b, int c, int d) { return abs(a - c) + abs(b - d); } int main() { int m, n, i, j, k, p; cin >> m >> n >> p; for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) { int num; cin >> num; v[num].push_back({i, j, 999999999}); } } i = 1; for (j = 0; j < v[i].size(); j++) { v[i][j].c = cost(v[i][j].a, v[i][j].b, 1, 1); } for (i = 2; i <= p; i++) { sort((v[i - 1]).begin(), (v[i - 1]).end()); for (j = 0; j < v[i].size(); j++) { for (k = 0; k < min((int)v[i - 1].size(), m + n + 2); k++) { v[i][j].c = min(v[i][j].c, v[i - 1][k].c + cost(v[i - 1][k].a, v[i - 1][k].b, v[i][j].a, v[i][j].b)); } } } int ans = 999999999; i = p; for (j = 0; j < v[i].size(); j++) ans = min(ans, v[i][j].c); cout << ans << endl; } ```
#include <bits/stdc++.h> using namespace std; inline int dist(const pair<int, int>& a, const pair<int, int>& b) { return abs(a.first - b.first) + abs(a.second - b.second); } void bfs(int n, int m, const vector<vector<int> >& a, const vector<pair<int, int> >& pPairs, const vector<vector<long long> >& dp, vector<vector<long long> >& dists) { priority_queue<pair<long long, pair<int, int> > > source; for (int i = 0; i < pPairs.size(); ++i) { source.push(make_pair(-dp[pPairs[i].first][pPairs[i].second], make_pair(pPairs[i].first, pPairs[i].second))); } queue<pair<int, int> > q; const pair<int, int>& firstPos = source.top().second; dists[firstPos.first][firstPos.second] = -source.top().first; q.push(make_pair(firstPos.first, firstPos.second)); source.pop(); while (!q.empty()) { const pair<int, int>& t = q.front(); while (!source.empty()) { const pair<long long, pair<int, int> >& s = source.top(); if (-s.first > dists[t.first][t.second]) { break; } dists[s.second.first][s.second.second] = -s.first; q.push(make_pair(s.second.first, s.second.second)); source.pop(); } if (t.first > 0) { pair<int, int> toAdd = make_pair(t.first - 1, t.second); if (dists[toAdd.first][toAdd.second] == LLONG_MAX) { dists[toAdd.first][toAdd.second] = min(dists[toAdd.first][toAdd.second], dists[t.first][t.second] + 1); q.push(make_pair(toAdd.first, toAdd.second)); } } if (t.first < n - 1) { pair<int, int> toAdd = make_pair(t.first + 1, t.second); if (dists[toAdd.first][toAdd.second] == LLONG_MAX) { dists[toAdd.first][toAdd.second] = min(dists[toAdd.first][toAdd.second], dists[t.first][t.second] + 1); q.push(make_pair(toAdd.first, toAdd.second)); } } if (t.second > 0) { pair<int, int> toAdd = make_pair(t.first, t.second - 1); if (dists[toAdd.first][toAdd.second] == LLONG_MAX) { dists[toAdd.first][toAdd.second] = min(dists[toAdd.first][toAdd.second], dists[t.first][t.second] + 1); q.push(make_pair(toAdd.first, toAdd.second)); } } if (t.second < m - 1) { pair<int, int> toAdd = make_pair(t.first, t.second + 1); if (dists[toAdd.first][toAdd.second] == LLONG_MAX) { dists[toAdd.first][toAdd.second] = min(dists[toAdd.first][toAdd.second], dists[t.first][t.second] + 1); q.push(make_pair(toAdd.first, toAdd.second)); } } q.pop(); } } long long Solve(int n, int m, int p, const vector<vector<int> >& a, const vector<vector<pair<int, int> > >& pToInd) { vector<vector<long long> > dp(n, vector<long long>(m, LLONG_MAX)); dp[pToInd[p][0].first][pToInd[p][0].second] = 0; for (int curP = p - 1; curP >= 1; --curP) { const vector<pair<int, int> >& curPPairs = pToInd[curP]; const vector<pair<int, int> >& curPPlusPairs = pToInd[curP + 1]; if (curPPairs.size() * curPPlusPairs.size() < m * n) { for (int i = 0; i < curPPairs.size(); ++i) { const pair<int, int>& curPair = curPPairs[i]; for (int j = 0; j < curPPlusPairs.size(); ++j) { const pair<int, int>& toPair = curPPlusPairs[j]; long long thisDist = dp[toPair.first][toPair.second] + dist(curPair, toPair); if (dp[curPair.first][curPair.second] > thisDist) { dp[curPair.first][curPair.second] = thisDist; } } } } else { vector<vector<long long> > dists(n, vector<long long>(m, LLONG_MAX)); bfs(n, m, a, curPPlusPairs, dp, dists); for (int i = 0; i < curPPairs.size(); ++i) { const pair<int, int>& curPair = curPPairs[i]; dp[curPair.first][curPair.second] = dists[curPair.first][curPair.second]; } } } if (a[0][0] == 1) { return dp[0][0]; } else { const vector<pair<int, int> >& curPPlusPairs = pToInd[1]; pair<int, int> curPair = make_pair(0, 0); long long result = LLONG_MAX; for (int j = 0; j < curPPlusPairs.size(); ++j) { long long thisDist = dp[curPPlusPairs[j].first][curPPlusPairs[j].second] + dist(curPair, curPPlusPairs[j]); if (result > thisDist) { result = thisDist; } } return result; } } int main() { iostream::sync_with_stdio(false); int n = 0; int m = 0; int p = 0; cin >> n >> m >> p; vector<vector<int> > a(n, vector<int>(m, 0)); vector<vector<pair<int, int> > > pToInd(p + 1, vector<pair<int, int> >()); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; pToInd[a[i][j]].push_back(make_pair(i, j)); } } cout << Solve(n, m, p, a, pToInd); 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; inline int dist(const pair<int, int>& a, const pair<int, int>& b) { return abs(a.first - b.first) + abs(a.second - b.second); } void bfs(int n, int m, const vector<vector<int> >& a, const vector<pair<int, int> >& pPairs, const vector<vector<long long> >& dp, vector<vector<long long> >& dists) { priority_queue<pair<long long, pair<int, int> > > source; for (int i = 0; i < pPairs.size(); ++i) { source.push(make_pair(-dp[pPairs[i].first][pPairs[i].second], make_pair(pPairs[i].first, pPairs[i].second))); } queue<pair<int, int> > q; const pair<int, int>& firstPos = source.top().second; dists[firstPos.first][firstPos.second] = -source.top().first; q.push(make_pair(firstPos.first, firstPos.second)); source.pop(); while (!q.empty()) { const pair<int, int>& t = q.front(); while (!source.empty()) { const pair<long long, pair<int, int> >& s = source.top(); if (-s.first > dists[t.first][t.second]) { break; } dists[s.second.first][s.second.second] = -s.first; q.push(make_pair(s.second.first, s.second.second)); source.pop(); } if (t.first > 0) { pair<int, int> toAdd = make_pair(t.first - 1, t.second); if (dists[toAdd.first][toAdd.second] == LLONG_MAX) { dists[toAdd.first][toAdd.second] = min(dists[toAdd.first][toAdd.second], dists[t.first][t.second] + 1); q.push(make_pair(toAdd.first, toAdd.second)); } } if (t.first < n - 1) { pair<int, int> toAdd = make_pair(t.first + 1, t.second); if (dists[toAdd.first][toAdd.second] == LLONG_MAX) { dists[toAdd.first][toAdd.second] = min(dists[toAdd.first][toAdd.second], dists[t.first][t.second] + 1); q.push(make_pair(toAdd.first, toAdd.second)); } } if (t.second > 0) { pair<int, int> toAdd = make_pair(t.first, t.second - 1); if (dists[toAdd.first][toAdd.second] == LLONG_MAX) { dists[toAdd.first][toAdd.second] = min(dists[toAdd.first][toAdd.second], dists[t.first][t.second] + 1); q.push(make_pair(toAdd.first, toAdd.second)); } } if (t.second < m - 1) { pair<int, int> toAdd = make_pair(t.first, t.second + 1); if (dists[toAdd.first][toAdd.second] == LLONG_MAX) { dists[toAdd.first][toAdd.second] = min(dists[toAdd.first][toAdd.second], dists[t.first][t.second] + 1); q.push(make_pair(toAdd.first, toAdd.second)); } } q.pop(); } } long long Solve(int n, int m, int p, const vector<vector<int> >& a, const vector<vector<pair<int, int> > >& pToInd) { vector<vector<long long> > dp(n, vector<long long>(m, LLONG_MAX)); dp[pToInd[p][0].first][pToInd[p][0].second] = 0; for (int curP = p - 1; curP >= 1; --curP) { const vector<pair<int, int> >& curPPairs = pToInd[curP]; const vector<pair<int, int> >& curPPlusPairs = pToInd[curP + 1]; if (curPPairs.size() * curPPlusPairs.size() < m * n) { for (int i = 0; i < curPPairs.size(); ++i) { const pair<int, int>& curPair = curPPairs[i]; for (int j = 0; j < curPPlusPairs.size(); ++j) { const pair<int, int>& toPair = curPPlusPairs[j]; long long thisDist = dp[toPair.first][toPair.second] + dist(curPair, toPair); if (dp[curPair.first][curPair.second] > thisDist) { dp[curPair.first][curPair.second] = thisDist; } } } } else { vector<vector<long long> > dists(n, vector<long long>(m, LLONG_MAX)); bfs(n, m, a, curPPlusPairs, dp, dists); for (int i = 0; i < curPPairs.size(); ++i) { const pair<int, int>& curPair = curPPairs[i]; dp[curPair.first][curPair.second] = dists[curPair.first][curPair.second]; } } } if (a[0][0] == 1) { return dp[0][0]; } else { const vector<pair<int, int> >& curPPlusPairs = pToInd[1]; pair<int, int> curPair = make_pair(0, 0); long long result = LLONG_MAX; for (int j = 0; j < curPPlusPairs.size(); ++j) { long long thisDist = dp[curPPlusPairs[j].first][curPPlusPairs[j].second] + dist(curPair, curPPlusPairs[j]); if (result > thisDist) { result = thisDist; } } return result; } } int main() { iostream::sync_with_stdio(false); int n = 0; int m = 0; int p = 0; cin >> n >> m >> p; vector<vector<int> > a(n, vector<int>(m, 0)); vector<vector<pair<int, int> > > pToInd(p + 1, vector<pair<int, int> >()); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; pToInd[a[i][j]].push_back(make_pair(i, j)); } } cout << Solve(n, m, p, a, pToInd); return 0; } ```
#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 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 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; struct _2D_Segment_Tree { struct _1D_Segment_Tree { int seg[310 * 4]; void modify(int l, int r, int y, int val, int idx) { if (l == r) { seg[idx] = val; } else { int mid = (l + r) >> 1; if (y <= mid) modify(l, mid, y, val, idx << 1); else modify(mid + 1, r, y, val, idx << 1 | 1); seg[idx] = min(seg[idx << 1], seg[idx << 1 | 1]); } } int query(int l, int r, int yl, int yr, int idx) { if (l == yl && r == yr) return seg[idx]; int mid = (l + r) >> 1; if (yr <= mid) return query(l, mid, yl, yr, idx << 1); else if (yl > mid) return query(mid + 1, r, yl, yr, idx << 1 | 1); return min(query(l, mid, yl, mid, idx << 1), query(mid + 1, r, mid + 1, yr, idx << 1 | 1)); } } tree[310 * 4]; void pushUp(int l, int r, int id, int idx, int pos) { if (l == r) { tree[id].seg[idx] = min(tree[id << 1].seg[idx], tree[id << 1 | 1].seg[idx]); } else { int mid = (l + r) >> 1; if (pos <= mid) pushUp(l, mid, id, idx << 1, pos); else pushUp(mid + 1, r, id, idx << 1 | 1, pos); tree[id].seg[idx] = min(tree[id << 1].seg[idx], tree[id << 1 | 1].seg[idx]); } } void modify(int l, int r, int x, int y, int val, int idx) { if (l == r) { tree[idx].modify(1, M, y, val, 1); } else { int mid = (l + r) >> 1; if (x <= mid) modify(l, mid, x, y, val, idx << 1); else modify(mid + 1, r, x, y, val, idx << 1 | 1); pushUp(1, M, idx, 1, y); } } int query(int l, int r, int xl, int xr, int yl, int yr, int idx) { if (l == xl && r == xr) return tree[idx].query(1, M, yl, yr, 1); int mid = (l + r) >> 1; if (xr <= mid) return query(l, mid, xl, xr, yl, yr, idx << 1); else if (xl > mid) return query(mid + 1, r, xl, xr, yl, yr, idx << 1 | 1); return min(query(l, mid, xl, mid, yl, yr, idx << 1), query(mid + 1, r, mid + 1, xr, yl, yr, idx << 1 | 1)); } } _2D_Tree[4]; vector<pair<int, int> > typePos[310 * 310]; vector<int> tmp; int grid[310][310]; int main() { scanf("%d%d%d", &N, &M, &P); memset(_2D_Tree, 0x3f, sizeof _2D_Tree); for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { scanf("%d", &grid[i][j]); typePos[grid[i][j]].push_back(pair<int, int>(i, j)); } } typePos[0].push_back(pair<int, int>(1, 1)); _2D_Tree[0].modify(1, N, 1, 1, -2, 1); _2D_Tree[1].modify(1, N, 1, 1, 0, 1); _2D_Tree[2].modify(1, N, 1, 1, 0, 1); _2D_Tree[3].modify(1, N, 1, 1, 2, 1); for (int type = 1; type <= P; type++) { tmp.clear(); for (int i = 0; i < (int)typePos[type].size(); i++) { tmp.push_back(0x7fffffff); tmp[i] = min(tmp[i], typePos[type][i].first + typePos[type][i].second + _2D_Tree[0].query(1, N, 1, typePos[type][i].first, 1, typePos[type][i].second, 1)); tmp[i] = min(tmp[i], -typePos[type][i].first + typePos[type][i].second + _2D_Tree[1].query(1, N, typePos[type][i].first, N, 1, typePos[type][i].second, 1)); tmp[i] = min(tmp[i], typePos[type][i].first - typePos[type][i].second + _2D_Tree[2].query(1, N, 1, typePos[type][i].first, typePos[type][i].second, M, 1)); tmp[i] = min(tmp[i], -typePos[type][i].first - typePos[type][i].second + _2D_Tree[3].query(1, N, typePos[type][i].first, N, typePos[type][i].second, M, 1)); } for (int i = 0; i < (int)typePos[type - 1].size(); i++) for (int j = 0; j < 4; j++) _2D_Tree[j].modify(1, N, typePos[type - 1][i].first, typePos[type - 1][i].second, 0x3f3f3f3f, 1); for (int i = 0; i < (int)typePos[type].size(); i++) { _2D_Tree[0].modify( 1, N, typePos[type][i].first, typePos[type][i].second, -typePos[type][i].first - typePos[type][i].second + tmp[i], 1); _2D_Tree[1].modify( 1, N, typePos[type][i].first, typePos[type][i].second, typePos[type][i].first - typePos[type][i].second + tmp[i], 1); _2D_Tree[2].modify( 1, N, typePos[type][i].first, typePos[type][i].second, -typePos[type][i].first + typePos[type][i].second + tmp[i], 1); _2D_Tree[3].modify( 1, N, typePos[type][i].first, typePos[type][i].second, typePos[type][i].first + typePos[type][i].second + tmp[i], 1); } } printf("%d\n", tmp[0]); 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; struct _2D_Segment_Tree { struct _1D_Segment_Tree { int seg[310 * 4]; void modify(int l, int r, int y, int val, int idx) { if (l == r) { seg[idx] = val; } else { int mid = (l + r) >> 1; if (y <= mid) modify(l, mid, y, val, idx << 1); else modify(mid + 1, r, y, val, idx << 1 | 1); seg[idx] = min(seg[idx << 1], seg[idx << 1 | 1]); } } int query(int l, int r, int yl, int yr, int idx) { if (l == yl && r == yr) return seg[idx]; int mid = (l + r) >> 1; if (yr <= mid) return query(l, mid, yl, yr, idx << 1); else if (yl > mid) return query(mid + 1, r, yl, yr, idx << 1 | 1); return min(query(l, mid, yl, mid, idx << 1), query(mid + 1, r, mid + 1, yr, idx << 1 | 1)); } } tree[310 * 4]; void pushUp(int l, int r, int id, int idx, int pos) { if (l == r) { tree[id].seg[idx] = min(tree[id << 1].seg[idx], tree[id << 1 | 1].seg[idx]); } else { int mid = (l + r) >> 1; if (pos <= mid) pushUp(l, mid, id, idx << 1, pos); else pushUp(mid + 1, r, id, idx << 1 | 1, pos); tree[id].seg[idx] = min(tree[id << 1].seg[idx], tree[id << 1 | 1].seg[idx]); } } void modify(int l, int r, int x, int y, int val, int idx) { if (l == r) { tree[idx].modify(1, M, y, val, 1); } else { int mid = (l + r) >> 1; if (x <= mid) modify(l, mid, x, y, val, idx << 1); else modify(mid + 1, r, x, y, val, idx << 1 | 1); pushUp(1, M, idx, 1, y); } } int query(int l, int r, int xl, int xr, int yl, int yr, int idx) { if (l == xl && r == xr) return tree[idx].query(1, M, yl, yr, 1); int mid = (l + r) >> 1; if (xr <= mid) return query(l, mid, xl, xr, yl, yr, idx << 1); else if (xl > mid) return query(mid + 1, r, xl, xr, yl, yr, idx << 1 | 1); return min(query(l, mid, xl, mid, yl, yr, idx << 1), query(mid + 1, r, mid + 1, xr, yl, yr, idx << 1 | 1)); } } _2D_Tree[4]; vector<pair<int, int> > typePos[310 * 310]; vector<int> tmp; int grid[310][310]; int main() { scanf("%d%d%d", &N, &M, &P); memset(_2D_Tree, 0x3f, sizeof _2D_Tree); for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { scanf("%d", &grid[i][j]); typePos[grid[i][j]].push_back(pair<int, int>(i, j)); } } typePos[0].push_back(pair<int, int>(1, 1)); _2D_Tree[0].modify(1, N, 1, 1, -2, 1); _2D_Tree[1].modify(1, N, 1, 1, 0, 1); _2D_Tree[2].modify(1, N, 1, 1, 0, 1); _2D_Tree[3].modify(1, N, 1, 1, 2, 1); for (int type = 1; type <= P; type++) { tmp.clear(); for (int i = 0; i < (int)typePos[type].size(); i++) { tmp.push_back(0x7fffffff); tmp[i] = min(tmp[i], typePos[type][i].first + typePos[type][i].second + _2D_Tree[0].query(1, N, 1, typePos[type][i].first, 1, typePos[type][i].second, 1)); tmp[i] = min(tmp[i], -typePos[type][i].first + typePos[type][i].second + _2D_Tree[1].query(1, N, typePos[type][i].first, N, 1, typePos[type][i].second, 1)); tmp[i] = min(tmp[i], typePos[type][i].first - typePos[type][i].second + _2D_Tree[2].query(1, N, 1, typePos[type][i].first, typePos[type][i].second, M, 1)); tmp[i] = min(tmp[i], -typePos[type][i].first - typePos[type][i].second + _2D_Tree[3].query(1, N, typePos[type][i].first, N, typePos[type][i].second, M, 1)); } for (int i = 0; i < (int)typePos[type - 1].size(); i++) for (int j = 0; j < 4; j++) _2D_Tree[j].modify(1, N, typePos[type - 1][i].first, typePos[type - 1][i].second, 0x3f3f3f3f, 1); for (int i = 0; i < (int)typePos[type].size(); i++) { _2D_Tree[0].modify( 1, N, typePos[type][i].first, typePos[type][i].second, -typePos[type][i].first - typePos[type][i].second + tmp[i], 1); _2D_Tree[1].modify( 1, N, typePos[type][i].first, typePos[type][i].second, typePos[type][i].first - typePos[type][i].second + tmp[i], 1); _2D_Tree[2].modify( 1, N, typePos[type][i].first, typePos[type][i].second, -typePos[type][i].first + typePos[type][i].second + tmp[i], 1); _2D_Tree[3].modify( 1, N, typePos[type][i].first, typePos[type][i].second, typePos[type][i].first + typePos[type][i].second + tmp[i], 1); } } printf("%d\n", tmp[0]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAXN = 310; const int INF = 1e9; const int S = 90000; int n, m, p; int mp[MAXN][MAXN]; int dist[MAXN][MAXN]; vector<pair<int, int>> g[MAXN][MAXN]; vector<pair<int, int>> fsz[MAXN * MAXN]; int pr(int i, int j) { if ((0 <= i) && (i <= n) && (0 <= j) && (j <= m)) { return true; } else { return false; } } void dijk(int c) { if (fsz[c].size() * fsz[c - 1].size() > S) { int min_zn = INF; for (auto e : fsz[c - 1]) { min_zn = min(min_zn, dist[e.first][e.second]); } for (auto e : fsz[c - 1]) { dist[e.first][e.second] -= min_zn; } vector<pair<int, int>> q[2 * MAXN]; for (auto e : fsz[c - 1]) { if (dist[e.first][e.second] < n + m) q[dist[e.first][e.second]].push_back(e); } for (int i = 0; i < n + m; ++i) { for (auto e1 : q[i]) { for (auto e2 : g[e1.first][e1.second]) { if (dist[e1.first][e1.second] + 1 < dist[e2.first][e2.second]) { q[dist[e1.first][e1.second] + 1].push_back(e2); dist[e2.first][e2.second] = dist[e1.first][e1.second] + 1; } } } } for (int j = 0; j < n; ++j) { for (int l = 0; l < m; ++l) { if (mp[j][l] != c) { dist[j][l] = INF; } else { dist[j][l] += min_zn; } } } } else { for (auto e1 : fsz[c - 1]) { for (auto e2 : fsz[c]) { dist[e2.first][e2.second] = min(dist[e2.first][e2.second], dist[e1.first][e1.second] + abs(e2.first - e1.first) + abs(e2.second - e1.second)); } } for (auto e1 : fsz[c - 1]) { dist[e1.first][e1.second] = INF; } if ((c == 1) && (fsz[1][0] == make_pair(0, 0))) { dist[0][0] = 0; } } } int main() { ios::sync_with_stdio(false); cout.tie(0); cin.tie(0); cin >> n >> m >> p; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> mp[i][j]; dist[i][j] = INF; fsz[mp[i][j]].push_back({i, j}); } } fsz[0].push_back({0, 0}); dist[0][0] = 0; vector<pair<int, int>> fg = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { for (auto e : fg) { if (pr(i + e.first, j + e.second)) { g[i][j].push_back({i + e.first, j + e.second}); } } } } for (int i = 1; i <= p; ++i) { dijk(i); } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (mp[i][j] == p) { cout << dist[i][j] << endl; return 0; } } } 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 MAXN = 310; const int INF = 1e9; const int S = 90000; int n, m, p; int mp[MAXN][MAXN]; int dist[MAXN][MAXN]; vector<pair<int, int>> g[MAXN][MAXN]; vector<pair<int, int>> fsz[MAXN * MAXN]; int pr(int i, int j) { if ((0 <= i) && (i <= n) && (0 <= j) && (j <= m)) { return true; } else { return false; } } void dijk(int c) { if (fsz[c].size() * fsz[c - 1].size() > S) { int min_zn = INF; for (auto e : fsz[c - 1]) { min_zn = min(min_zn, dist[e.first][e.second]); } for (auto e : fsz[c - 1]) { dist[e.first][e.second] -= min_zn; } vector<pair<int, int>> q[2 * MAXN]; for (auto e : fsz[c - 1]) { if (dist[e.first][e.second] < n + m) q[dist[e.first][e.second]].push_back(e); } for (int i = 0; i < n + m; ++i) { for (auto e1 : q[i]) { for (auto e2 : g[e1.first][e1.second]) { if (dist[e1.first][e1.second] + 1 < dist[e2.first][e2.second]) { q[dist[e1.first][e1.second] + 1].push_back(e2); dist[e2.first][e2.second] = dist[e1.first][e1.second] + 1; } } } } for (int j = 0; j < n; ++j) { for (int l = 0; l < m; ++l) { if (mp[j][l] != c) { dist[j][l] = INF; } else { dist[j][l] += min_zn; } } } } else { for (auto e1 : fsz[c - 1]) { for (auto e2 : fsz[c]) { dist[e2.first][e2.second] = min(dist[e2.first][e2.second], dist[e1.first][e1.second] + abs(e2.first - e1.first) + abs(e2.second - e1.second)); } } for (auto e1 : fsz[c - 1]) { dist[e1.first][e1.second] = INF; } if ((c == 1) && (fsz[1][0] == make_pair(0, 0))) { dist[0][0] = 0; } } } int main() { ios::sync_with_stdio(false); cout.tie(0); cin.tie(0); cin >> n >> m >> p; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> mp[i][j]; dist[i][j] = INF; fsz[mp[i][j]].push_back({i, j}); } } fsz[0].push_back({0, 0}); dist[0][0] = 0; vector<pair<int, int>> fg = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { for (auto e : fg) { if (pr(i + e.first, j + e.second)) { g[i][j].push_back({i + e.first, j + e.second}); } } } } for (int i = 1; i <= p; ++i) { dijk(i); } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (mp[i][j] == p) { cout << dist[i][j] << endl; return 0; } } } return 0; } ```
#include <bits/stdc++.h> using namespace std; long long dp[333][333]; int a[333][333]; int fq[333 * 333]; vector<pair<int, int> > pos[333 * 333]; long long dt[333][333]; int main() { ios_base::sync_with_stdio(); cin.tie(0); int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int ii = 0; ii < m; ii++) { cin >> a[i][ii]; fq[a[i][ii]]++; pos[a[i][ii]].push_back({i, ii}); if (a[i][ii] == 1) { dp[i][ii] = i + ii; } else { dp[i][ii] = 1e18; } } } for (int k = 1; k < p; k++) { if ((long long)fq[k] * (long long)fq[k + 1] > (long long)n * (long long)m * (long long)10) { priority_queue<pair<long long, pair<int, int> > > dij; for (int i = 0; i < n; i++) { for (int ii = 0; ii < m; ii++) { dt[i][ii] = 1e18; } } for (auto t : pos[k]) { dij.push({-dp[t.first][t.second], {t.first, t.second}}); } while (!dij.empty()) { auto x = dij.top(); dij.pop(); long long d = -x.first; if (dt[x.second.first][x.second.second] <= d) continue; dt[x.second.first][x.second.second] = d; for (int i = -1; i <= 1; i++) { for (int ii = -1; ii <= 1; ii++) { if ((i == 0) ^ (ii == 0)) { int ny = x.second.first + i; int nx = x.second.second + ii; if (ny < 0 || ny >= n || nx < 0 || nx >= m) continue; if (dt[ny][nx] <= d + 1) continue; dij.push({-d - 1, {ny, nx}}); } } } } for (auto t : pos[k + 1]) { dp[t.first][t.second] = dt[t.first][t.second]; } } else { for (auto t : pos[k]) { for (auto tt : pos[k + 1]) { dp[tt.first][tt.second] = min( dp[tt.first][tt.second], dp[t.first][t.second] + (long long)(abs(t.first - tt.first) + abs(t.second - tt.second))); } } } } for (int i = 0; i < n; i++) { for (int ii = 0; ii < m; ii++) { if (a[i][ii] == p) { cout << dp[i][ii] << 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> using namespace std; long long dp[333][333]; int a[333][333]; int fq[333 * 333]; vector<pair<int, int> > pos[333 * 333]; long long dt[333][333]; int main() { ios_base::sync_with_stdio(); cin.tie(0); int n, m, p; cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int ii = 0; ii < m; ii++) { cin >> a[i][ii]; fq[a[i][ii]]++; pos[a[i][ii]].push_back({i, ii}); if (a[i][ii] == 1) { dp[i][ii] = i + ii; } else { dp[i][ii] = 1e18; } } } for (int k = 1; k < p; k++) { if ((long long)fq[k] * (long long)fq[k + 1] > (long long)n * (long long)m * (long long)10) { priority_queue<pair<long long, pair<int, int> > > dij; for (int i = 0; i < n; i++) { for (int ii = 0; ii < m; ii++) { dt[i][ii] = 1e18; } } for (auto t : pos[k]) { dij.push({-dp[t.first][t.second], {t.first, t.second}}); } while (!dij.empty()) { auto x = dij.top(); dij.pop(); long long d = -x.first; if (dt[x.second.first][x.second.second] <= d) continue; dt[x.second.first][x.second.second] = d; for (int i = -1; i <= 1; i++) { for (int ii = -1; ii <= 1; ii++) { if ((i == 0) ^ (ii == 0)) { int ny = x.second.first + i; int nx = x.second.second + ii; if (ny < 0 || ny >= n || nx < 0 || nx >= m) continue; if (dt[ny][nx] <= d + 1) continue; dij.push({-d - 1, {ny, nx}}); } } } } for (auto t : pos[k + 1]) { dp[t.first][t.second] = dt[t.first][t.second]; } } else { for (auto t : pos[k]) { for (auto tt : pos[k + 1]) { dp[tt.first][tt.second] = min( dp[tt.first][tt.second], dp[t.first][t.second] + (long long)(abs(t.first - tt.first) + abs(t.second - tt.second))); } } } } for (int i = 0; i < n; i++) { for (int ii = 0; ii < m; ii++) { if (a[i][ii] == p) { cout << dp[i][ii] << endl; return 0; } } } } ```
#include <bits/stdc++.h> #pragma GCC optizie("3", "Ofast", "inline") #pragma GCC target("avx") using namespace std; inline long long read() { long long x = 0; char ch = getchar(); bool f = 0; for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = 1; for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0'; return f ? -x : x; } void write(long long x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) write(x / 10); putchar(x % 10 + '0'); } void writeln(long long x) { write(x); putchar('\n'); } void writep(long long x) { write(x); putchar(' '); } long long const N = 300 + 3; long long const inf = 1e18; long long dx[4] = {0, 0, 1, -1}; long long dy[4] = {1, -1, 0, 0}; long long n, m, k, d[N][N]; struct node { long long x, y, step; }; queue<node> q; vector<node> a[N * N]; long long dis(long long x1, long long y1, long long x2, long long y2) { return abs(x1 - x2) + abs(y1 - y2); } void bfs(long long id) { while (!q.empty()) q.pop(); memset(d, 0x3f, sizeof(d)); for (long long i = 0; i < a[id].size(); i++) q.push((node){a[id][i].x, a[id][i].y}), d[a[id][i].x][a[id][i].y] = a[id][i].step; while (!q.empty()) { node now = q.front(); q.pop(); for (long long i = 0; i < 4; i++) { long long fx = now.x + dx[i]; long long fy = now.y + dy[i]; if (fx < 1 || fy < 1 || fx > n || fy > m || d[fx][fy] <= d[now.x][now.y] + 1) continue; d[fx][fy] = d[now.x][now.y] + 1; q.push((node){fx, fy}); } } } signed main() { n = read(); m = read(); k = read(); for (long long i = 1; i <= n; i++) for (long long j = 1; j <= m; j++) { long long x = read(); if (x == 1) a[x].push_back((node){i, j, i + j - 2}); else a[x].push_back((node){i, j, inf}); } for (long long i = 2; i <= k; i++) { if (a[i - 1].size() * a[i].size() <= n * m) for (long long j = 0; j < a[i - 1].size(); j++) for (long long l = 0; l < a[i].size(); l++) a[i][l].step = min( a[i][l].step, a[i - 1][j].step + dis(a[i - 1][j].x, a[i - 1][j].y, a[i][l].x, a[i][l].y)); else { bfs(i - 1); for (long long j = 0; j < a[i].size(); j++) a[i][j].step = d[a[i][j].x][a[i][j].y]; } } long long ans = 1e18; for (long long i = 0; i < a[k].size(); i++) ans = min(ans, a[k][i].step); writeln(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> #pragma GCC optizie("3", "Ofast", "inline") #pragma GCC target("avx") using namespace std; inline long long read() { long long x = 0; char ch = getchar(); bool f = 0; for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = 1; for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0'; return f ? -x : x; } void write(long long x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) write(x / 10); putchar(x % 10 + '0'); } void writeln(long long x) { write(x); putchar('\n'); } void writep(long long x) { write(x); putchar(' '); } long long const N = 300 + 3; long long const inf = 1e18; long long dx[4] = {0, 0, 1, -1}; long long dy[4] = {1, -1, 0, 0}; long long n, m, k, d[N][N]; struct node { long long x, y, step; }; queue<node> q; vector<node> a[N * N]; long long dis(long long x1, long long y1, long long x2, long long y2) { return abs(x1 - x2) + abs(y1 - y2); } void bfs(long long id) { while (!q.empty()) q.pop(); memset(d, 0x3f, sizeof(d)); for (long long i = 0; i < a[id].size(); i++) q.push((node){a[id][i].x, a[id][i].y}), d[a[id][i].x][a[id][i].y] = a[id][i].step; while (!q.empty()) { node now = q.front(); q.pop(); for (long long i = 0; i < 4; i++) { long long fx = now.x + dx[i]; long long fy = now.y + dy[i]; if (fx < 1 || fy < 1 || fx > n || fy > m || d[fx][fy] <= d[now.x][now.y] + 1) continue; d[fx][fy] = d[now.x][now.y] + 1; q.push((node){fx, fy}); } } } signed main() { n = read(); m = read(); k = read(); for (long long i = 1; i <= n; i++) for (long long j = 1; j <= m; j++) { long long x = read(); if (x == 1) a[x].push_back((node){i, j, i + j - 2}); else a[x].push_back((node){i, j, inf}); } for (long long i = 2; i <= k; i++) { if (a[i - 1].size() * a[i].size() <= n * m) for (long long j = 0; j < a[i - 1].size(); j++) for (long long l = 0; l < a[i].size(); l++) a[i][l].step = min( a[i][l].step, a[i - 1][j].step + dis(a[i - 1][j].x, a[i - 1][j].y, a[i][l].x, a[i][l].y)); else { bfs(i - 1); for (long long j = 0; j < a[i].size(); j++) a[i][j].step = d[a[i][j].x][a[i][j].y]; } } long long ans = 1e18; for (long long i = 0; i < a[k].size(); i++) ans = min(ans, a[k][i].step); writeln(ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; template <class T> T sqr(T x) { return x * x; } template <class T> T gcd(T a, T b) { return (b != 0 ? gcd<T>(b, a % b) : a); } template <class T> T lcm(T a, T b) { return (a / gcd<T>(a, b) * b); } template <class T> inline T bigmod(T p, T e, T M) { if (e == 0) return 1; if (e % 2 == 0) { long long int t = bigmod(p, e / 2, M); return (T)((t * t) % M); } return (T)((long long int)bigmod(p, e - 1, M) * (long long int)p) % M; } template <class T> inline T bigexp(T p, T e) { if (e == 0) return 1; if (e % 2 == 0) { long long int t = bigexp(p, e / 2); return (T)((t * t)); } return (T)((long long int)bigexp(p, e - 1) * (long long int)p); } template <class T> inline T modinverse(T a, T M) { return bigmod(a, M - 2, M); } int dx4[] = {1, 0, -1, 0}; int dy4[] = {0, 1, 0, -1}; int dx8[] = {1, 1, 0, -1, -1, -1, 0, 1}; int dy8[] = {0, 1, 1, 1, 0, -1, -1, -1}; int nx8[] = {1, 1, -1, -1, 2, 2, -2, -2}; int ny8[] = {2, -2, 2, -2, 1, -1, 1, -1}; int month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; struct T { int val, r, c; }; int n, m, p, dp[305][305], a; vector<pair<int, int> > v[90002]; pair<int, int> pp, qq; bool valid(int r, int c) { return (r >= 1 && r <= n && c >= 1 && c <= m); } void bfs(int id) { queue<T> q; T u, vv; for (int i = 0; i < v[id - 1].size(); i++) { pp = v[id - 1][i]; u.val = dp[pp.first][pp.second]; u.r = pp.first; u.c = pp.second; q.push(u); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) dp[i][j] = 2000000000; for (int i = 0; i < v[id - 1].size(); i++) { pp = v[id - 1][i]; dp[pp.first][pp.second] = 0; } while (!q.empty()) { u = q.front(); q.pop(); for (int k = 0; k < 4; k++) { vv.r = u.r + dx4[k]; vv.c = u.c + dy4[k]; vv.val = u.val + 1; if (valid(vv.r, vv.c)) { if (dp[vv.r][vv.c] > vv.val) { dp[vv.r][vv.c] = vv.val; q.push(vv); } } } } } int main() { scanf("%d %d %d", &n, &m, &p); for (__typeof(n) i = (1); i <= (n); i++) for (__typeof(m) j = (1); j <= (m); j++) { scanf("%d", &a); pp.first = i; pp.second = j; v[a].push_back(pp); } for (int i = 0; i < v[1].size(); i++) { pp = v[1][i]; dp[pp.first][pp.second] = pp.first - 1 + pp.second - 1; } for (int i = 2; i <= p; i++) { if (v[i - 1].size() * v[i].size() <= n * m) { for (int j = 0; j < v[i].size(); j++) { pp = v[i][j]; dp[pp.first][pp.second] = 2000000000; } for (int j = 0; j < v[i - 1].size(); j++) { pp = v[i - 1][j]; for (int k = 0; k < v[i].size(); k++) { qq = v[i][k]; dp[qq.first][qq.second] = min(dp[qq.first][qq.second], dp[pp.first][pp.second] + abs(pp.first - qq.first) + abs(pp.second - qq.second)); } } } else { bfs(i); } } printf("%d", dp[v[p][0].first][v[p][0].second]); 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; template <class T> T sqr(T x) { return x * x; } template <class T> T gcd(T a, T b) { return (b != 0 ? gcd<T>(b, a % b) : a); } template <class T> T lcm(T a, T b) { return (a / gcd<T>(a, b) * b); } template <class T> inline T bigmod(T p, T e, T M) { if (e == 0) return 1; if (e % 2 == 0) { long long int t = bigmod(p, e / 2, M); return (T)((t * t) % M); } return (T)((long long int)bigmod(p, e - 1, M) * (long long int)p) % M; } template <class T> inline T bigexp(T p, T e) { if (e == 0) return 1; if (e % 2 == 0) { long long int t = bigexp(p, e / 2); return (T)((t * t)); } return (T)((long long int)bigexp(p, e - 1) * (long long int)p); } template <class T> inline T modinverse(T a, T M) { return bigmod(a, M - 2, M); } int dx4[] = {1, 0, -1, 0}; int dy4[] = {0, 1, 0, -1}; int dx8[] = {1, 1, 0, -1, -1, -1, 0, 1}; int dy8[] = {0, 1, 1, 1, 0, -1, -1, -1}; int nx8[] = {1, 1, -1, -1, 2, 2, -2, -2}; int ny8[] = {2, -2, 2, -2, 1, -1, 1, -1}; int month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; struct T { int val, r, c; }; int n, m, p, dp[305][305], a; vector<pair<int, int> > v[90002]; pair<int, int> pp, qq; bool valid(int r, int c) { return (r >= 1 && r <= n && c >= 1 && c <= m); } void bfs(int id) { queue<T> q; T u, vv; for (int i = 0; i < v[id - 1].size(); i++) { pp = v[id - 1][i]; u.val = dp[pp.first][pp.second]; u.r = pp.first; u.c = pp.second; q.push(u); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) dp[i][j] = 2000000000; for (int i = 0; i < v[id - 1].size(); i++) { pp = v[id - 1][i]; dp[pp.first][pp.second] = 0; } while (!q.empty()) { u = q.front(); q.pop(); for (int k = 0; k < 4; k++) { vv.r = u.r + dx4[k]; vv.c = u.c + dy4[k]; vv.val = u.val + 1; if (valid(vv.r, vv.c)) { if (dp[vv.r][vv.c] > vv.val) { dp[vv.r][vv.c] = vv.val; q.push(vv); } } } } } int main() { scanf("%d %d %d", &n, &m, &p); for (__typeof(n) i = (1); i <= (n); i++) for (__typeof(m) j = (1); j <= (m); j++) { scanf("%d", &a); pp.first = i; pp.second = j; v[a].push_back(pp); } for (int i = 0; i < v[1].size(); i++) { pp = v[1][i]; dp[pp.first][pp.second] = pp.first - 1 + pp.second - 1; } for (int i = 2; i <= p; i++) { if (v[i - 1].size() * v[i].size() <= n * m) { for (int j = 0; j < v[i].size(); j++) { pp = v[i][j]; dp[pp.first][pp.second] = 2000000000; } for (int j = 0; j < v[i - 1].size(); j++) { pp = v[i - 1][j]; for (int k = 0; k < v[i].size(); k++) { qq = v[i][k]; dp[qq.first][qq.second] = min(dp[qq.first][qq.second], dp[pp.first][pp.second] + abs(pp.first - qq.first) + abs(pp.second - qq.second)); } } } else { bfs(i); } } printf("%d", dp[v[p][0].first][v[p][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; int break_point() { char c; while ((c = getchar()) != '\n') ; return 0; } template <typename T> void read_integer(T &r) { bool sign = 0; r = 0; char c; while (1) { c = getchar(); if (c == '-') { sign = 1; break; } if (c != ' ' && c != '\n') { r = c - '0'; break; } } while (1) { c = getchar(); if (c == ' ' || c == '\n') break; r = r * 10 + (c - '0'); } if (sign) r = -r; } long long binpowmod(long long a, long long b, long long mod) { long long res = 1; while (b) { if (b & 1) { res *= a; res %= mod; b--; } else { a *= a; a %= mod; b >>= 1; } } return res; } long long binpow(long long a, long long b) { long long res = 1; while (b) { if (b & 1) { res *= a; b--; } else { a *= a; b >>= 1; } } return res; } inline int getbit(int x, int b) { return (x >> b) & 1; } inline long long getbit(long long x, int b) { return (x >> b) & 1; } inline unsigned long long getbit(unsigned long long x, int b) { return (x >> b) & 1; } inline int setbit(int x, int b) { return x | (1 << b); } inline void _setbit(int &x, int b) { x = setbit(x, b); } inline long long setbit(long long x, int b) { return x | (1ll << b); } inline void _setbit(long long &x, int b) { x = setbit(x, b); } inline int unsetbit(int x, int b) { return x & (INT_MAX - (1 << b)); } inline void _unsetbit(int &x, int b) { x = unsetbit(x, b); } inline int countbit(int x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); return ((x + (x >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } inline long long countbit(long long x) { int p1 = (x >> 32) & ((1ll << 32) - 1); int p2 = x & ((1ll << 32) - 1); return countbit(p1) + countbit(p2); } template <typename T> void printbit(T x, int len) { for (int i = len - 1; i >= 0; i--) printf("%d", getbit(x, i)); } int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } template <typename A, typename B> ostream &operator<<(ostream &stream, const pair<A, B> &p) { stream << "{" << p.first << "," << p.second << "}"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const vector<A> &v) { stream << "["; for (auto itr = v.begin(); itr != v.end(); itr++) stream << *itr << " "; stream << "]"; return stream; } template <typename A, typename B> ostream &operator<<(ostream &stream, const map<A, B> &v) { stream << "["; for (auto itr = v.begin(); itr != v.end(); itr++) stream << *itr << " "; stream << "]"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const set<A> &v) { stream << "["; for (auto itr = v.begin(); itr != v.end(); itr++) stream << *itr << " "; stream << "]"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const stack<A> &v) { stack<A> st = v; stream << "["; while (!st.empty()) { stream << st.top() << " "; st.pop(); } stream << "]"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const priority_queue<A> &v) { priority_queue<A> q = v; stream << "["; while (!q.empty()) { stream << q.top() << " "; q.pop(); } stream << "]"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const queue<A> &v) { queue<A> q = v; stream << "["; while (!q.empty()) { stream << q.front() << " "; q.pop(); } stream << "]"; return stream; } void run(); int main() { srand(time(NULL)); do { run(); if (0) { 0 ? printf("-------------------------------\n") : 0; 0 ? printf("-------------------------------\n") : 0; 0 ? break_point() : 0; } } while (0); return 0; } const int mod = 1e9 + 7; const long long INF = 1e12; struct Point { int x, y; Point(int _x = 0, int _y = 0) : x(_x), y(_y) {} long long dist(const Point &other) const { return abs(x - other.x) + abs(y - other.y); } }; long long dp[305][305]; int a[305][305]; long long d[305][305]; int TM = 1; int u[305][305]; vector<Point> g[100005]; int dt[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; void run() { 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) { read_integer(a[i][j]); g[a[i][j]].push_back(Point(i, j)); dp[i][j] = a[i][j] == 1 ? i + j : INF; } } sort(g[1].begin(), g[1].end(), [](const Point &a, const Point &b) { return dp[a.x][a.y] < dp[b.x][b.y]; }); for (int curp = 2; curp <= p; ++curp) { if (((int)g[curp - 1].size()) * ((int)g[curp].size()) > n * m) { TM++; queue<Point> q; q.push(g[curp - 1][0]); u[q.front().x][q.front().y] = TM; d[q.front().x][q.front().y] = dp[q.front().x][q.front().y]; int ptr = 1; while (ptr < ((int)g[curp - 1].size()) && d[q.front().x][q.front().y] == dp[g[curp - 1][ptr].x][g[curp - 1][ptr].y]) { u[g[curp - 1][ptr].x][g[curp - 1][ptr].y] = TM; d[g[curp - 1][ptr].x][g[curp - 1][ptr].y] = dp[g[curp - 1][ptr].x][g[curp - 1][ptr].y]; q.push(g[curp - 1][ptr]); ptr++; } while (!q.empty()) { Point cur = q.front(); q.pop(); while (ptr < ((int)g[curp - 1].size()) && d[cur.x][cur.y] + 1 == dp[g[curp - 1][ptr].x][g[curp - 1][ptr].y]) { u[g[curp - 1][ptr].x][g[curp - 1][ptr].y] = TM; d[g[curp - 1][ptr].x][g[curp - 1][ptr].y] = dp[g[curp - 1][ptr].x][g[curp - 1][ptr].y]; q.push(g[curp - 1][ptr]); ptr++; } for (int t = 0; t < 4; ++t) { int x = cur.x + dt[t][0]; int y = cur.y + dt[t][1]; if (x >= 0 && x < n && y >= 0 && y < m) { if (u[x][y] != TM) { d[x][y] = INF; u[x][y] = TM; } if (d[x][y] > d[cur.x][cur.y] + 1) { d[x][y] = d[cur.x][cur.y] + 1; q.push(Point(x, y)); } } } } for (int i = 0; i < ((int)g[curp].size()); ++i) { Point &cur = g[curp][i]; dp[cur.x][cur.y] = d[cur.x][cur.y]; } } else { for (int i = 0; i < ((int)g[curp].size()); ++i) { Point &cur = g[curp][i]; for (int j = 0; j < ((int)g[curp - 1].size()); ++j) { Point &prv = g[curp - 1][j]; dp[cur.x][cur.y] = min((dp[cur.x][cur.y]), (dp[prv.x][prv.y] + cur.dist(prv))); } } } sort(g[curp].begin(), g[curp].end(), [](const Point &a, const Point &b) { return dp[a.x][a.y] < dp[b.x][b.y]; }); } long long res = LLONG_MAX; for (int i = 0; i < ((int)g[p].size()); ++i) res = min((res), (dp[g[p][i].x][g[p][i].y])); printf(0 ? "%lld" : "%I64d", res); putchar('\n'); }
### 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 break_point() { char c; while ((c = getchar()) != '\n') ; return 0; } template <typename T> void read_integer(T &r) { bool sign = 0; r = 0; char c; while (1) { c = getchar(); if (c == '-') { sign = 1; break; } if (c != ' ' && c != '\n') { r = c - '0'; break; } } while (1) { c = getchar(); if (c == ' ' || c == '\n') break; r = r * 10 + (c - '0'); } if (sign) r = -r; } long long binpowmod(long long a, long long b, long long mod) { long long res = 1; while (b) { if (b & 1) { res *= a; res %= mod; b--; } else { a *= a; a %= mod; b >>= 1; } } return res; } long long binpow(long long a, long long b) { long long res = 1; while (b) { if (b & 1) { res *= a; b--; } else { a *= a; b >>= 1; } } return res; } inline int getbit(int x, int b) { return (x >> b) & 1; } inline long long getbit(long long x, int b) { return (x >> b) & 1; } inline unsigned long long getbit(unsigned long long x, int b) { return (x >> b) & 1; } inline int setbit(int x, int b) { return x | (1 << b); } inline void _setbit(int &x, int b) { x = setbit(x, b); } inline long long setbit(long long x, int b) { return x | (1ll << b); } inline void _setbit(long long &x, int b) { x = setbit(x, b); } inline int unsetbit(int x, int b) { return x & (INT_MAX - (1 << b)); } inline void _unsetbit(int &x, int b) { x = unsetbit(x, b); } inline int countbit(int x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); return ((x + (x >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } inline long long countbit(long long x) { int p1 = (x >> 32) & ((1ll << 32) - 1); int p2 = x & ((1ll << 32) - 1); return countbit(p1) + countbit(p2); } template <typename T> void printbit(T x, int len) { for (int i = len - 1; i >= 0; i--) printf("%d", getbit(x, i)); } int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } template <typename A, typename B> ostream &operator<<(ostream &stream, const pair<A, B> &p) { stream << "{" << p.first << "," << p.second << "}"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const vector<A> &v) { stream << "["; for (auto itr = v.begin(); itr != v.end(); itr++) stream << *itr << " "; stream << "]"; return stream; } template <typename A, typename B> ostream &operator<<(ostream &stream, const map<A, B> &v) { stream << "["; for (auto itr = v.begin(); itr != v.end(); itr++) stream << *itr << " "; stream << "]"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const set<A> &v) { stream << "["; for (auto itr = v.begin(); itr != v.end(); itr++) stream << *itr << " "; stream << "]"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const stack<A> &v) { stack<A> st = v; stream << "["; while (!st.empty()) { stream << st.top() << " "; st.pop(); } stream << "]"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const priority_queue<A> &v) { priority_queue<A> q = v; stream << "["; while (!q.empty()) { stream << q.top() << " "; q.pop(); } stream << "]"; return stream; } template <typename A> ostream &operator<<(ostream &stream, const queue<A> &v) { queue<A> q = v; stream << "["; while (!q.empty()) { stream << q.front() << " "; q.pop(); } stream << "]"; return stream; } void run(); int main() { srand(time(NULL)); do { run(); if (0) { 0 ? printf("-------------------------------\n") : 0; 0 ? printf("-------------------------------\n") : 0; 0 ? break_point() : 0; } } while (0); return 0; } const int mod = 1e9 + 7; const long long INF = 1e12; struct Point { int x, y; Point(int _x = 0, int _y = 0) : x(_x), y(_y) {} long long dist(const Point &other) const { return abs(x - other.x) + abs(y - other.y); } }; long long dp[305][305]; int a[305][305]; long long d[305][305]; int TM = 1; int u[305][305]; vector<Point> g[100005]; int dt[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; void run() { 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) { read_integer(a[i][j]); g[a[i][j]].push_back(Point(i, j)); dp[i][j] = a[i][j] == 1 ? i + j : INF; } } sort(g[1].begin(), g[1].end(), [](const Point &a, const Point &b) { return dp[a.x][a.y] < dp[b.x][b.y]; }); for (int curp = 2; curp <= p; ++curp) { if (((int)g[curp - 1].size()) * ((int)g[curp].size()) > n * m) { TM++; queue<Point> q; q.push(g[curp - 1][0]); u[q.front().x][q.front().y] = TM; d[q.front().x][q.front().y] = dp[q.front().x][q.front().y]; int ptr = 1; while (ptr < ((int)g[curp - 1].size()) && d[q.front().x][q.front().y] == dp[g[curp - 1][ptr].x][g[curp - 1][ptr].y]) { u[g[curp - 1][ptr].x][g[curp - 1][ptr].y] = TM; d[g[curp - 1][ptr].x][g[curp - 1][ptr].y] = dp[g[curp - 1][ptr].x][g[curp - 1][ptr].y]; q.push(g[curp - 1][ptr]); ptr++; } while (!q.empty()) { Point cur = q.front(); q.pop(); while (ptr < ((int)g[curp - 1].size()) && d[cur.x][cur.y] + 1 == dp[g[curp - 1][ptr].x][g[curp - 1][ptr].y]) { u[g[curp - 1][ptr].x][g[curp - 1][ptr].y] = TM; d[g[curp - 1][ptr].x][g[curp - 1][ptr].y] = dp[g[curp - 1][ptr].x][g[curp - 1][ptr].y]; q.push(g[curp - 1][ptr]); ptr++; } for (int t = 0; t < 4; ++t) { int x = cur.x + dt[t][0]; int y = cur.y + dt[t][1]; if (x >= 0 && x < n && y >= 0 && y < m) { if (u[x][y] != TM) { d[x][y] = INF; u[x][y] = TM; } if (d[x][y] > d[cur.x][cur.y] + 1) { d[x][y] = d[cur.x][cur.y] + 1; q.push(Point(x, y)); } } } } for (int i = 0; i < ((int)g[curp].size()); ++i) { Point &cur = g[curp][i]; dp[cur.x][cur.y] = d[cur.x][cur.y]; } } else { for (int i = 0; i < ((int)g[curp].size()); ++i) { Point &cur = g[curp][i]; for (int j = 0; j < ((int)g[curp - 1].size()); ++j) { Point &prv = g[curp - 1][j]; dp[cur.x][cur.y] = min((dp[cur.x][cur.y]), (dp[prv.x][prv.y] + cur.dist(prv))); } } } sort(g[curp].begin(), g[curp].end(), [](const Point &a, const Point &b) { return dp[a.x][a.y] < dp[b.x][b.y]; }); } long long res = LLONG_MAX; for (int i = 0; i < ((int)g[p].size()); ++i) res = min((res), (dp[g[p][i].x][g[p][i].y])); printf(0 ? "%lld" : "%I64d", res); putchar('\n'); } ```
#include <bits/stdc++.h> using namespace std; const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; int n, m, p; int dist[90055]; vector<int> vec[90055]; int main() { scanf("%d %d %d", &n, &m, &p); int x; vec[0].emplace_back(0); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &x); vec[x].emplace_back(i * m + j); } } memset(dist, 63, sizeof(dist)); dist[0] = 0; for (int level = 0; level < p; level++) { if (level == 1 && find(vec[1].begin(), vec[1].end(), 0) == vec[1].end()) dist[0] = (int)1e9; if (vec[level + 1].size() * vec[level].size() <= 90000) { for (auto u : vec[level]) { int x = u / m, y = u % m; for (auto v : vec[level + 1]) { int nx = v / m, ny = v % m; dist[v] = min(dist[v], dist[u] + abs(x - nx) + abs(y - ny)); } } continue; } vector<bool> in_que(n * m, false); vector<int> d(n * m, (int)1e9); queue<int> que; for (auto u : vec[level]) { d[u] = dist[u]; que.push(u); } while (!que.empty()) { int u = que.front(); que.pop(); in_que[u] = false; int x = u / m, y = u % m; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; int v = nx * m + ny; if (nx >= 0 && nx < n && ny >= 0 && ny < m && d[v] > d[u] + 1) { d[v] = d[u] + 1; if (!in_que[v]) { in_que[v] = true; que.push(v); } } } } for (auto u : vec[level + 1]) dist[u] = d[u]; } int res = INT_MAX; for (auto u : vec[p]) res = min(res, dist[u]); printf("%d\n", res); 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 dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; int n, m, p; int dist[90055]; vector<int> vec[90055]; int main() { scanf("%d %d %d", &n, &m, &p); int x; vec[0].emplace_back(0); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &x); vec[x].emplace_back(i * m + j); } } memset(dist, 63, sizeof(dist)); dist[0] = 0; for (int level = 0; level < p; level++) { if (level == 1 && find(vec[1].begin(), vec[1].end(), 0) == vec[1].end()) dist[0] = (int)1e9; if (vec[level + 1].size() * vec[level].size() <= 90000) { for (auto u : vec[level]) { int x = u / m, y = u % m; for (auto v : vec[level + 1]) { int nx = v / m, ny = v % m; dist[v] = min(dist[v], dist[u] + abs(x - nx) + abs(y - ny)); } } continue; } vector<bool> in_que(n * m, false); vector<int> d(n * m, (int)1e9); queue<int> que; for (auto u : vec[level]) { d[u] = dist[u]; que.push(u); } while (!que.empty()) { int u = que.front(); que.pop(); in_que[u] = false; int x = u / m, y = u % m; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; int v = nx * m + ny; if (nx >= 0 && nx < n && ny >= 0 && ny < m && d[v] > d[u] + 1) { d[v] = d[u] + 1; if (!in_que[v]) { in_que[v] = true; que.push(v); } } } } for (auto u : vec[level + 1]) dist[u] = d[u]; } int res = INT_MAX; for (auto u : vec[p]) res = min(res, dist[u]); printf("%d\n", res); return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p, dp[305][305]; vector<pair<int, int> > a[90005]; template <class T> inline void RD(T &a) { register int ch = getchar(); bool ng = 0; for (; ch < '0' || ch > '9'; ch = getchar()) if (ch == '-') ng = 1; for (a = 0; ch >= '0' && ch <= '9'; ch = getchar()) a = (a << 1) + (a << 3) + (ch ^ '0'); if (ng) a = ~a + 1; } struct BIT { int t[305][305]; void init() { for (int i(1), b_(n); i <= b_; ++i) for (int j(1), b_(m); j <= b_; ++j) t[i][j] = 1e9; } void upd(int x, int y, int v) { for (int i = x; i <= n; i += (i & (-i))) for (int j = y; j <= m; j += (j & (-j))) t[i][j] = min(t[i][j], v); } int get(int x, int y) { int res = 1e9; for (int i = x; i; i -= (i & (-i))) for (int j = y; j; j -= (j & (-j))) res = min(res, t[i][j]); return res; } void reset(int x, int y) { for (int i = x; i <= n; i += (i & (-i))) for (int j = y; j <= m; j += (j & (-j))) t[i][j] = 1e9; } } TL, TR, BL, BR; int main() { RD(n), RD(m), RD(p); for (int i(1), b_(n); i <= b_; ++i) for (int j(1), b_(m); j <= b_; ++j) { int x; RD(x); a[x].emplace_back(i, j); dp[i][j] = (x == 1) ? (i + j - 2) : 1e9; } TL.init(), TR.init(), BL.init(), BR.init(); for (int i(0), b_((int)(a[1].size()) - 1); i <= b_; ++i) { int x = a[1][i].first, y = a[1][i].second; TL.upd(x, y, dp[x][y] - x - y); TR.upd(x, m + 1 - y, dp[x][y] - x + y); BR.upd(n + 1 - x, m + 1 - y, dp[x][y] + x + y); BL.upd(n + 1 - x, y, dp[x][y] + x - y); } for (int i(2), b_(p); i <= b_; ++i) { for (int j(0), b_((int)(a[i].size()) - 1); j <= b_; ++j) { int x = a[i][j].first, y = a[i][j].second; dp[x][y] = min(dp[x][y], TL.get(x, y) + x + y); dp[x][y] = min(dp[x][y], TR.get(x, m + 1 - y) + x - y); dp[x][y] = min(dp[x][y], BR.get(n + 1 - x, m + 1 - y) - x - y); dp[x][y] = min(dp[x][y], BL.get(n + 1 - x, y) - x + y); } if (i == p) continue; for (int j(0), b_((int)(a[i - 1].size()) - 1); j <= b_; ++j) { int x = a[i - 1][j].first, y = a[i - 1][j].second; TL.reset(x, y); TR.reset(x, m + 1 - y); BR.reset(n + 1 - x, m + 1 - y); BL.reset(n + 1 - x, y); } for (int j(0), b_((int)(a[i].size()) - 1); j <= b_; ++j) { int x = a[i][j].first, y = a[i][j].second; TL.upd(x, y, dp[x][y] - x - y); TR.upd(x, m + 1 - y, dp[x][y] - x + y); BR.upd(n + 1 - x, m + 1 - y, dp[x][y] + x + y); BL.upd(n + 1 - x, y, dp[x][y] + x - y); } } printf("%d", dp[a[p][0].first][a[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; int n, m, p, dp[305][305]; vector<pair<int, int> > a[90005]; template <class T> inline void RD(T &a) { register int ch = getchar(); bool ng = 0; for (; ch < '0' || ch > '9'; ch = getchar()) if (ch == '-') ng = 1; for (a = 0; ch >= '0' && ch <= '9'; ch = getchar()) a = (a << 1) + (a << 3) + (ch ^ '0'); if (ng) a = ~a + 1; } struct BIT { int t[305][305]; void init() { for (int i(1), b_(n); i <= b_; ++i) for (int j(1), b_(m); j <= b_; ++j) t[i][j] = 1e9; } void upd(int x, int y, int v) { for (int i = x; i <= n; i += (i & (-i))) for (int j = y; j <= m; j += (j & (-j))) t[i][j] = min(t[i][j], v); } int get(int x, int y) { int res = 1e9; for (int i = x; i; i -= (i & (-i))) for (int j = y; j; j -= (j & (-j))) res = min(res, t[i][j]); return res; } void reset(int x, int y) { for (int i = x; i <= n; i += (i & (-i))) for (int j = y; j <= m; j += (j & (-j))) t[i][j] = 1e9; } } TL, TR, BL, BR; int main() { RD(n), RD(m), RD(p); for (int i(1), b_(n); i <= b_; ++i) for (int j(1), b_(m); j <= b_; ++j) { int x; RD(x); a[x].emplace_back(i, j); dp[i][j] = (x == 1) ? (i + j - 2) : 1e9; } TL.init(), TR.init(), BL.init(), BR.init(); for (int i(0), b_((int)(a[1].size()) - 1); i <= b_; ++i) { int x = a[1][i].first, y = a[1][i].second; TL.upd(x, y, dp[x][y] - x - y); TR.upd(x, m + 1 - y, dp[x][y] - x + y); BR.upd(n + 1 - x, m + 1 - y, dp[x][y] + x + y); BL.upd(n + 1 - x, y, dp[x][y] + x - y); } for (int i(2), b_(p); i <= b_; ++i) { for (int j(0), b_((int)(a[i].size()) - 1); j <= b_; ++j) { int x = a[i][j].first, y = a[i][j].second; dp[x][y] = min(dp[x][y], TL.get(x, y) + x + y); dp[x][y] = min(dp[x][y], TR.get(x, m + 1 - y) + x - y); dp[x][y] = min(dp[x][y], BR.get(n + 1 - x, m + 1 - y) - x - y); dp[x][y] = min(dp[x][y], BL.get(n + 1 - x, y) - x + y); } if (i == p) continue; for (int j(0), b_((int)(a[i - 1].size()) - 1); j <= b_; ++j) { int x = a[i - 1][j].first, y = a[i - 1][j].second; TL.reset(x, y); TR.reset(x, m + 1 - y); BR.reset(n + 1 - x, m + 1 - y); BL.reset(n + 1 - x, y); } for (int j(0), b_((int)(a[i].size()) - 1); j <= b_; ++j) { int x = a[i][j].first, y = a[i][j].second; TL.upd(x, y, dp[x][y] - x - y); TR.upd(x, m + 1 - y, dp[x][y] - x + y); BR.upd(n + 1 - x, m + 1 - y, dp[x][y] + x + y); BL.upd(n + 1 - x, y, dp[x][y] + x - y); } } printf("%d", dp[a[p][0].first][a[p][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; vector<pair<pair<int, int>, long long> > place[90004]; vector<pair<int, long long> > temp[305]; vector<long long> MIN[2][305]; int bin(int i, int j, const int &b, const int &x) { if (i == j) return i; if (i == j - 1) { if (temp[x][i].first >= b) return i; return j; } int mid = (i + j) >> 1; if (temp[x][mid].first >= b) return bin(i, mid, b, x); return bin(mid + 1, j, b, x); } long long rq(int x, int b) { int idx = bin(0, temp[x].size() - 1, b, x); if (!idx) return MIN[1][x][idx] - b; else return min(MIN[1][x][idx] - b, b + MIN[0][x][idx - 1]); } int main() { int n, m, p; scanf("%d", &n); scanf("%d", &m); scanf("%d", &p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); if (x == 1) place[x].push_back(make_pair(make_pair(i, j), abs(i - 1) + abs(j - 1))); else place[x].push_back(make_pair(make_pair(i, j), 0)); } } for (int i = 1; i < p; i++) { for (int j = 1; j <= n; j++) temp[j].clear(); for (int j = 0; j < place[i].size(); j++) temp[place[i][j].first.first].push_back( make_pair(place[i][j].first.second, place[i][j].second)); for (int x = 1; x <= n; x++) { temp[x].push_back(make_pair(302, 1e18)); sort(temp[x].begin(), temp[x].end()); MIN[0][x].resize(temp[x].size()); MIN[1][x].resize(temp[x].size()); MIN[0][x][0] = temp[x][0].second - temp[x][0].first; for (int i = 1; i < temp[x].size(); i++) MIN[0][x][i] = min(MIN[0][x][i - 1], temp[x][i].second - temp[x][i].first); int last = temp[x].size() - 1; MIN[1][x][last] = temp[x][last].first + temp[x][last].second; for (int i = last - 1; i >= 0; i--) MIN[1][x][i] = min(MIN[1][x][i + 1], temp[x][i].first + temp[x][i].second); } for (int j = 0; j < place[i + 1].size(); j++) { long long mn = 1000000007 * 1LL * 1000000007; for (int x = 1; x <= n; x++) { long long ans = abs(x - place[i + 1][j].first.first); ans += rq(x, place[i + 1][j].first.second); if (ans < mn) mn = ans; } place[i + 1][j].second = mn; } } long long ans = 1000000007 * 1LL * 1000000007; for (int i = 0; i < place[p].size(); i++) ans = min(ans, place[p][i].second); printf("%lld\n", ans); }
### 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; vector<pair<pair<int, int>, long long> > place[90004]; vector<pair<int, long long> > temp[305]; vector<long long> MIN[2][305]; int bin(int i, int j, const int &b, const int &x) { if (i == j) return i; if (i == j - 1) { if (temp[x][i].first >= b) return i; return j; } int mid = (i + j) >> 1; if (temp[x][mid].first >= b) return bin(i, mid, b, x); return bin(mid + 1, j, b, x); } long long rq(int x, int b) { int idx = bin(0, temp[x].size() - 1, b, x); if (!idx) return MIN[1][x][idx] - b; else return min(MIN[1][x][idx] - b, b + MIN[0][x][idx - 1]); } int main() { int n, m, p; scanf("%d", &n); scanf("%d", &m); scanf("%d", &p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int x; scanf("%d", &x); if (x == 1) place[x].push_back(make_pair(make_pair(i, j), abs(i - 1) + abs(j - 1))); else place[x].push_back(make_pair(make_pair(i, j), 0)); } } for (int i = 1; i < p; i++) { for (int j = 1; j <= n; j++) temp[j].clear(); for (int j = 0; j < place[i].size(); j++) temp[place[i][j].first.first].push_back( make_pair(place[i][j].first.second, place[i][j].second)); for (int x = 1; x <= n; x++) { temp[x].push_back(make_pair(302, 1e18)); sort(temp[x].begin(), temp[x].end()); MIN[0][x].resize(temp[x].size()); MIN[1][x].resize(temp[x].size()); MIN[0][x][0] = temp[x][0].second - temp[x][0].first; for (int i = 1; i < temp[x].size(); i++) MIN[0][x][i] = min(MIN[0][x][i - 1], temp[x][i].second - temp[x][i].first); int last = temp[x].size() - 1; MIN[1][x][last] = temp[x][last].first + temp[x][last].second; for (int i = last - 1; i >= 0; i--) MIN[1][x][i] = min(MIN[1][x][i + 1], temp[x][i].first + temp[x][i].second); } for (int j = 0; j < place[i + 1].size(); j++) { long long mn = 1000000007 * 1LL * 1000000007; for (int x = 1; x <= n; x++) { long long ans = abs(x - place[i + 1][j].first.first); ans += rq(x, place[i + 1][j].first.second); if (ans < mn) mn = ans; } place[i + 1][j].second = mn; } } long long ans = 1000000007 * 1LL * 1000000007; for (int i = 0; i < place[p].size(); i++) ans = min(ans, place[p][i].second); printf("%lld\n", ans); } ```
#include <bits/stdc++.h> using namespace std; const int N = 305; const int INF = (int)1e9; int a[N][N]; int dp[N][N]; vector<pair<int, int>> ps[N * N]; int help[N][N]; int dst(pair<int, int> x, pair<int, int> y) { return abs(x.first - y.first) + abs(x.second - y.second); } int main() { int n, m, p; scanf("%d%d%d", &n, &m, &p); int fx = 0, fy = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { scanf("%d", &a[i][j]); dp[i][j] = (a[i][j] == 1 ? i + j : INF); ps[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == p) fx = i, fy = j; } for (int i = 2; i <= p; ++i) { if (ps[i - 1].size() < N) { for (pair<int, int> cur : ps[i]) for (pair<int, int> lst : ps[i - 1]) dp[cur.first][cur.second] = min(dp[cur.first][cur.second], dp[lst.first][lst.second] + dst(cur, lst)); } else { for (int x = 0; x < n; ++x) fill(help[x], help[x] + m, INF); for (pair<int, int> lst : ps[i - 1]) for (int y = 0; y < m; ++y) help[lst.first][y] = min(help[lst.first][y], dp[lst.first][lst.second] + abs(lst.second - y)); for (pair<int, int> cur : ps[i]) for (int x = 0; x < n; ++x) dp[cur.first][cur.second] = min(dp[cur.first][cur.second], help[x][cur.second] + abs(x - cur.first)); } } cout << dp[fx][fy]; 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; const int INF = (int)1e9; int a[N][N]; int dp[N][N]; vector<pair<int, int>> ps[N * N]; int help[N][N]; int dst(pair<int, int> x, pair<int, int> y) { return abs(x.first - y.first) + abs(x.second - y.second); } int main() { int n, m, p; scanf("%d%d%d", &n, &m, &p); int fx = 0, fy = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { scanf("%d", &a[i][j]); dp[i][j] = (a[i][j] == 1 ? i + j : INF); ps[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == p) fx = i, fy = j; } for (int i = 2; i <= p; ++i) { if (ps[i - 1].size() < N) { for (pair<int, int> cur : ps[i]) for (pair<int, int> lst : ps[i - 1]) dp[cur.first][cur.second] = min(dp[cur.first][cur.second], dp[lst.first][lst.second] + dst(cur, lst)); } else { for (int x = 0; x < n; ++x) fill(help[x], help[x] + m, INF); for (pair<int, int> lst : ps[i - 1]) for (int y = 0; y < m; ++y) help[lst.first][y] = min(help[lst.first][y], dp[lst.first][lst.second] + abs(lst.second - y)); for (pair<int, int> cur : ps[i]) for (int x = 0; x < n; ++x) dp[cur.first][cur.second] = min(dp[cur.first][cur.second], help[x][cur.second] + abs(x - cur.first)); } } cout << dp[fx][fy]; return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p; int a[312][312]; vector<pair<int, pair<int, int> > > tab[312 * 312]; int d[312][312]; int vis[312][312]; int x[4] = {0, 0, 1, -1}; int y[4] = {1, -1, 0, 0}; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> p; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) cin >> a[i][j]; int start = 1; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) tab[a[i][j]].push_back(make_pair(0x3f3f3f3f, pair<int, int>(i, j))); for (int i = 0; i < tab[start].size(); ++i) { tab[start][i].first = tab[start][i].second.first + tab[start][i].second.second; } for (int i = start + 1; i <= p; ++i) { if (tab[i].size() * tab[i - 1].size() >= n * m) { for (int t1 = 0; t1 < n; ++t1) for (int t2 = 0; t2 < m; ++t2) d[t1][t2] = 0x3f3f3f3f, vis[t1][t2] = 0; queue<pair<int, pair<int, int> > > Q; sort(tab[i - 1].begin(), tab[i - 1].end()); int j = 0; Q.push(tab[i - 1][j++]); d[tab[i - 1][0].second.first][tab[i - 1][0].second.second] = tab[i - 1][0].first; while (!Q.empty()) { pair<int, pair<int, int> > p = Q.front(); Q.pop(); int e = p.second.first; int f = p.second.second; vis[e][f] = 1; int g = p.first; while (j < tab[i - 1].size() && g == tab[i - 1][j].first) { if (!vis[tab[i - 1][j].second.first][tab[i - 1][j].second.second]) { vis[tab[i - 1][j].second.first][tab[i - 1][j].second.second] = 1; d[tab[i - 1][j].second.first][tab[i - 1][j].second.second] = tab[i - 1][j].first; Q.push(tab[i - 1][j]); } j++; } for (int k = 0; k < 4; ++k) { int d1 = e + x[k]; int d2 = f + y[k]; if (d1 >= 0 && d1 < n && d2 >= 0 && d2 < m && !vis[d1][d2]) { d[d1][d2] = d[e][f] + 1; vis[d1][d2] = 1; Q.push(make_pair(d[d1][d2], pair<int, int>(d1, d2))); } } } for (int k = 0; k < tab[i].size(); ++k) { tab[i][k].first = d[tab[i][k].second.first][tab[i][k].second.second]; } continue; } for (int j = 0; j < tab[i].size(); ++j) { for (int k = 0; k < tab[i - 1].size(); ++k) { int d1 = abs(tab[i][j].second.first - tab[i - 1][k].second.first); int d2 = abs(tab[i][j].second.second - tab[i - 1][k].second.second); tab[i][j].first = min(tab[i][j].first, tab[i - 1][k].first + d1 + d2); } } } cout << tab[p][0].first << endl; 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 a[312][312]; vector<pair<int, pair<int, int> > > tab[312 * 312]; int d[312][312]; int vis[312][312]; int x[4] = {0, 0, 1, -1}; int y[4] = {1, -1, 0, 0}; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> p; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) cin >> a[i][j]; int start = 1; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) tab[a[i][j]].push_back(make_pair(0x3f3f3f3f, pair<int, int>(i, j))); for (int i = 0; i < tab[start].size(); ++i) { tab[start][i].first = tab[start][i].second.first + tab[start][i].second.second; } for (int i = start + 1; i <= p; ++i) { if (tab[i].size() * tab[i - 1].size() >= n * m) { for (int t1 = 0; t1 < n; ++t1) for (int t2 = 0; t2 < m; ++t2) d[t1][t2] = 0x3f3f3f3f, vis[t1][t2] = 0; queue<pair<int, pair<int, int> > > Q; sort(tab[i - 1].begin(), tab[i - 1].end()); int j = 0; Q.push(tab[i - 1][j++]); d[tab[i - 1][0].second.first][tab[i - 1][0].second.second] = tab[i - 1][0].first; while (!Q.empty()) { pair<int, pair<int, int> > p = Q.front(); Q.pop(); int e = p.second.first; int f = p.second.second; vis[e][f] = 1; int g = p.first; while (j < tab[i - 1].size() && g == tab[i - 1][j].first) { if (!vis[tab[i - 1][j].second.first][tab[i - 1][j].second.second]) { vis[tab[i - 1][j].second.first][tab[i - 1][j].second.second] = 1; d[tab[i - 1][j].second.first][tab[i - 1][j].second.second] = tab[i - 1][j].first; Q.push(tab[i - 1][j]); } j++; } for (int k = 0; k < 4; ++k) { int d1 = e + x[k]; int d2 = f + y[k]; if (d1 >= 0 && d1 < n && d2 >= 0 && d2 < m && !vis[d1][d2]) { d[d1][d2] = d[e][f] + 1; vis[d1][d2] = 1; Q.push(make_pair(d[d1][d2], pair<int, int>(d1, d2))); } } } for (int k = 0; k < tab[i].size(); ++k) { tab[i][k].first = d[tab[i][k].second.first][tab[i][k].second.second]; } continue; } for (int j = 0; j < tab[i].size(); ++j) { for (int k = 0; k < tab[i - 1].size(); ++k) { int d1 = abs(tab[i][j].second.first - tab[i - 1][k].second.first); int d2 = abs(tab[i][j].second.second - tab[i - 1][k].second.second); tab[i][j].first = min(tab[i][j].first, tab[i - 1][k].first + d1 + d2); } } } cout << tab[p][0].first << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; struct node { int x; int y; int z; node() {} node(int x1, int y1, int z1) : x(x1), y(y1), z(z1) {} }; int f[310][310]; int MAX = 2000000000; vector<node> v[90010]; int main() { int n, m, p; cin >> n >> m >> p; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { int mid; cin >> mid; v[mid].push_back(node(i, j, MAX)); } } for (int i = 0; i < v[1].size(); ++i) v[1][i].z = abs(1 - v[1][i].x) + abs(1 - v[1][i].y); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) f[i][j] = MAX; for (int i = 1; i < p; ++i) { for (int j = 0; j < v[i].size(); ++j) for (int k = 1; k <= m; ++k) f[v[i][j].x][k] = min(f[v[i][j].x][k], v[i][j].z + abs(k - v[i][j].y)); for (int j = 0; j < v[i + 1].size(); ++j) for (int k = 1; k <= n; ++k) v[i + 1][j].z = min(v[i + 1][j].z, f[k][v[i + 1][j].y] + abs(k - v[i + 1][j].x)); for (int j = 0; j < v[i].size(); ++j) for (int k = 1; k <= m; ++k) f[v[i][j].x][k] = MAX; } cout << v[p][0].z; }
### 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; struct node { int x; int y; int z; node() {} node(int x1, int y1, int z1) : x(x1), y(y1), z(z1) {} }; int f[310][310]; int MAX = 2000000000; vector<node> v[90010]; int main() { int n, m, p; cin >> n >> m >> p; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { int mid; cin >> mid; v[mid].push_back(node(i, j, MAX)); } } for (int i = 0; i < v[1].size(); ++i) v[1][i].z = abs(1 - v[1][i].x) + abs(1 - v[1][i].y); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) f[i][j] = MAX; for (int i = 1; i < p; ++i) { for (int j = 0; j < v[i].size(); ++j) for (int k = 1; k <= m; ++k) f[v[i][j].x][k] = min(f[v[i][j].x][k], v[i][j].z + abs(k - v[i][j].y)); for (int j = 0; j < v[i + 1].size(); ++j) for (int k = 1; k <= n; ++k) v[i + 1][j].z = min(v[i + 1][j].z, f[k][v[i + 1][j].y] + abs(k - v[i + 1][j].x)); for (int j = 0; j < v[i].size(); ++j) for (int k = 1; k <= m; ++k) f[v[i][j].x][k] = MAX; } cout << v[p][0].z; } ```
#include <bits/stdc++.h> using namespace std; int dp[500][500]; int maze[500][500]; vector<pair<int, int> > where[100100]; int dx[4] = {0, -1, 0, 1}; int dy[4] = {1, 0, -1, 0}; int mark[500][500]; int main(void) { int n, m, p; scanf("%d %d %d", &n, &m, &p); int fx, fy; int ans = 1e8; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dp[i][j] = 1000000000; scanf("%d", &maze[i][j]); where[maze[i][j]].push_back({i, j}); if (maze[i][j] == p) { dp[i][j] = 0; fx = i, fy = j; if (p == 1) ans = abs(i - 1) + abs(j - 1); } } } for (int i = p - 1; i >= 0; i--) { if (max(where[i].size(), where[i + 1].size()) <= sqrt(n * m)) { for (int j = 0; j < where[i].size(); j++) { int cx = where[i][j].first, cy = where[i][j].second; for (int k = 0; k < where[i + 1].size(); k++) { int nx = where[i + 1][k].first, ny = where[i + 1][k].second; dp[cx][cy] = min(dp[cx][cy], dp[nx][ny] + abs(nx - cx) + abs(ny - cy)); } if (i == 1) ans = min(ans, dp[cx][cy] + abs(cx - 1) + abs(cy - 1)); } } else { memset(mark, 0, sizeof(mark)); vector<pair<int, pair<int, int> > > vc; for (int j = 0; j < where[i + 1].size(); j++) { int cx = where[i + 1][j].first, cy = where[i + 1][j].second; vc.push_back({dp[cx][cy], {cx, cy}}); } sort(vc.begin(), vc.end()); queue<pair<int, pair<int, int> > > q; q.push(vc[0]); int cnt = 1; while (!q.empty()) { pair<int, pair<int, int> > cur = q.front(); q.pop(); int x = cur.second.first, y = cur.second.second; int wt = cur.first; if (maze[x][y] == i) { dp[x][y] = wt; } while (cnt < vc.size() && vc[cnt].first <= wt) { q.push(vc[cnt]); cnt++; } for (int d = 0; d < 4; d++) { int nx = x + dx[d], ny = y + dy[d]; if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && mark[nx][ny] == 0) { mark[nx][ny] = 1; q.push({wt + 1, {nx, ny}}); } } } for (int j = 0; j < where[i].size(); j++) { int cx = where[i][j].first, cy = where[i][j].second; if (i == 1) ans = min(ans, dp[cx][cy] + abs(cx - 1) + abs(cy - 1)); } } } 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; int dp[500][500]; int maze[500][500]; vector<pair<int, int> > where[100100]; int dx[4] = {0, -1, 0, 1}; int dy[4] = {1, 0, -1, 0}; int mark[500][500]; int main(void) { int n, m, p; scanf("%d %d %d", &n, &m, &p); int fx, fy; int ans = 1e8; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dp[i][j] = 1000000000; scanf("%d", &maze[i][j]); where[maze[i][j]].push_back({i, j}); if (maze[i][j] == p) { dp[i][j] = 0; fx = i, fy = j; if (p == 1) ans = abs(i - 1) + abs(j - 1); } } } for (int i = p - 1; i >= 0; i--) { if (max(where[i].size(), where[i + 1].size()) <= sqrt(n * m)) { for (int j = 0; j < where[i].size(); j++) { int cx = where[i][j].first, cy = where[i][j].second; for (int k = 0; k < where[i + 1].size(); k++) { int nx = where[i + 1][k].first, ny = where[i + 1][k].second; dp[cx][cy] = min(dp[cx][cy], dp[nx][ny] + abs(nx - cx) + abs(ny - cy)); } if (i == 1) ans = min(ans, dp[cx][cy] + abs(cx - 1) + abs(cy - 1)); } } else { memset(mark, 0, sizeof(mark)); vector<pair<int, pair<int, int> > > vc; for (int j = 0; j < where[i + 1].size(); j++) { int cx = where[i + 1][j].first, cy = where[i + 1][j].second; vc.push_back({dp[cx][cy], {cx, cy}}); } sort(vc.begin(), vc.end()); queue<pair<int, pair<int, int> > > q; q.push(vc[0]); int cnt = 1; while (!q.empty()) { pair<int, pair<int, int> > cur = q.front(); q.pop(); int x = cur.second.first, y = cur.second.second; int wt = cur.first; if (maze[x][y] == i) { dp[x][y] = wt; } while (cnt < vc.size() && vc[cnt].first <= wt) { q.push(vc[cnt]); cnt++; } for (int d = 0; d < 4; d++) { int nx = x + dx[d], ny = y + dy[d]; if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && mark[nx][ny] == 0) { mark[nx][ny] = 1; q.push({wt + 1, {nx, ny}}); } } } for (int j = 0; j < where[i].size(); j++) { int cx = where[i][j].first, cy = where[i][j].second; if (i == 1) ans = min(ans, dp[cx][cy] + abs(cx - 1) + abs(cy - 1)); } } } printf("%d\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int N = 305; int n, m, p; int dp[N][N]; vector<int> r[N]; vector<pair<int, int> > g[N * N]; int dis(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } void gao(int x, int y) { for (int i = 1; i <= n; i++) { int v = lower_bound(r[i].begin(), r[i].end(), y) - r[i].begin(); if (v - 1 >= 0) { dp[i][r[i][v - 1]] = min(dp[i][r[i][v - 1]], dp[x][y] + dis(x, y, i, r[i][v - 1])); } if (v < r[i].size()) { dp[i][r[i][v]] = min(dp[i][r[i][v]], dp[x][y] + dis(x, y, i, r[i][v])); } } } int main() { int ex, ey; scanf("%d%d%d", &n, &m, &p); int x, s; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dp[i][j] = INF; scanf("%d", &x); g[x].push_back(make_pair(i, j)); if (x == 1) { dp[i][j] = dis(1, 1, i, j); } if (x == p) { ex = i; ey = j; } } } for (int i = 1; i < p; i++) { for (int j = 1; j <= n; j++) r[j].clear(); for (int j = 0; j < g[i + 1].size(); j++) { int x = g[i + 1][j].first; int y = g[i + 1][j].second; r[x].push_back(y); } for (int j = 0; j < g[i].size(); j++) { int x = g[i][j].first; int y = g[i][j].second; if (dp[x][y] == INF) continue; gao(x, y); } } printf("%d\n", dp[ex][ey]); 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; const int INF = 0x3f3f3f3f; const int N = 305; int n, m, p; int dp[N][N]; vector<int> r[N]; vector<pair<int, int> > g[N * N]; int dis(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } void gao(int x, int y) { for (int i = 1; i <= n; i++) { int v = lower_bound(r[i].begin(), r[i].end(), y) - r[i].begin(); if (v - 1 >= 0) { dp[i][r[i][v - 1]] = min(dp[i][r[i][v - 1]], dp[x][y] + dis(x, y, i, r[i][v - 1])); } if (v < r[i].size()) { dp[i][r[i][v]] = min(dp[i][r[i][v]], dp[x][y] + dis(x, y, i, r[i][v])); } } } int main() { int ex, ey; scanf("%d%d%d", &n, &m, &p); int x, s; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dp[i][j] = INF; scanf("%d", &x); g[x].push_back(make_pair(i, j)); if (x == 1) { dp[i][j] = dis(1, 1, i, j); } if (x == p) { ex = i; ey = j; } } } for (int i = 1; i < p; i++) { for (int j = 1; j <= n; j++) r[j].clear(); for (int j = 0; j < g[i + 1].size(); j++) { int x = g[i + 1][j].first; int y = g[i + 1][j].second; r[x].push_back(y); } for (int j = 0; j < g[i].size(); j++) { int x = g[i][j].first; int y = g[i][j].second; if (dp[x][y] == INF) continue; gao(x, y); } } printf("%d\n", dp[ex][ey]); return 0; } ```
#include <bits/stdc++.h> using namespace std; queue<pair<int, int> > Q; vector<pair<int, int> > T[301 * 301]; int R, C, P, A[301][301], D[301][301], RM[4] = {0, 0, 1, -1}, CM[4] = {1, -1, 0, 0}; bool valid(int r, int c) { return 0 <= r && r < R && 0 <= c && c < C; } bool cmp(const pair<int, int>& A, const pair<int, int>& B) { return D[A.first][A.second] < D[B.first][B.second]; } void bfs(int p) { int dist[301][301], K = 0; memset(dist, -1, sizeof(dist)); sort(T[p].begin(), T[p].end(), cmp); while (true) { if (K < T[p].size()) { Q.push({T[p][K].first, T[p][K].second}); dist[Q.front().first][Q.front().second] = D[Q.front().first][Q.front().second]; } while (K < T[p].size() && D[T[p][K].first][T[p][K].second] == D[Q.front().first][Q.front().second]) { dist[T[p][K].first][T[p][K].second] = D[T[p][K].first][T[p][K].second]; Q.push({T[p][K].first, T[p][K].second}); K++; } if (Q.empty()) break; while (!Q.empty()) { int r = Q.front().first; int c = Q.front().second; Q.pop(); for (int k = 0; k < (int)4; k++) { int rr = r + RM[k]; int cc = c + CM[k]; if (valid(rr, cc) && dist[rr][cc] == -1 && A[rr][cc] != p) { dist[rr][cc] = dist[r][c] + 1; Q.push({rr, cc}); } } while (K < T[p].size() && D[T[p][K].first][T[p][K].second] == dist[r][c] + 1) { dist[T[p][K].first][T[p][K].second] = D[T[p][K].first][T[p][K].second]; Q.push({T[p][K].first, T[p][K].second}); K++; } } } for (int r = 0; r < (int)R; r++) for (int c = 0; c < (int)C; c++) if (A[r][c] == p + 1) D[r][c] = dist[r][c]; } int main() { scanf("%d %d\n", &R, &C); scanf("%d\n", &P); for (int r = 0; r < (int)R; r++) for (int c = 0; c < (int)C; c++) { scanf("%d\n", &A[r][c]); T[A[r][c]].push_back({r, c}); D[r][c] = int(1e9); } for (int i = 0; i < (int)T[1].size(); i++) { int r = T[1][i].first; int c = T[1][i].second; D[r][c] = r + c; } for (int p = 1; p < (int)P; p++) { if (T[p].size() * T[p + 1].size() >= R * C) { bfs(p); } else { for (int i = 0; i < (int)T[p].size(); i++) { int r1 = T[p][i].first; int c1 = T[p][i].second; for (int j = 0; j < (int)T[p + 1].size(); j++) { int r2 = T[p + 1][j].first; int c2 = T[p + 1][j].second; D[r2][c2] = min(D[r2][c2], D[r1][c1] + abs(r1 - r2) + abs(c1 - c2)); } } } } printf("%d\n", D[T[P][0].first][T[P][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; queue<pair<int, int> > Q; vector<pair<int, int> > T[301 * 301]; int R, C, P, A[301][301], D[301][301], RM[4] = {0, 0, 1, -1}, CM[4] = {1, -1, 0, 0}; bool valid(int r, int c) { return 0 <= r && r < R && 0 <= c && c < C; } bool cmp(const pair<int, int>& A, const pair<int, int>& B) { return D[A.first][A.second] < D[B.first][B.second]; } void bfs(int p) { int dist[301][301], K = 0; memset(dist, -1, sizeof(dist)); sort(T[p].begin(), T[p].end(), cmp); while (true) { if (K < T[p].size()) { Q.push({T[p][K].first, T[p][K].second}); dist[Q.front().first][Q.front().second] = D[Q.front().first][Q.front().second]; } while (K < T[p].size() && D[T[p][K].first][T[p][K].second] == D[Q.front().first][Q.front().second]) { dist[T[p][K].first][T[p][K].second] = D[T[p][K].first][T[p][K].second]; Q.push({T[p][K].first, T[p][K].second}); K++; } if (Q.empty()) break; while (!Q.empty()) { int r = Q.front().first; int c = Q.front().second; Q.pop(); for (int k = 0; k < (int)4; k++) { int rr = r + RM[k]; int cc = c + CM[k]; if (valid(rr, cc) && dist[rr][cc] == -1 && A[rr][cc] != p) { dist[rr][cc] = dist[r][c] + 1; Q.push({rr, cc}); } } while (K < T[p].size() && D[T[p][K].first][T[p][K].second] == dist[r][c] + 1) { dist[T[p][K].first][T[p][K].second] = D[T[p][K].first][T[p][K].second]; Q.push({T[p][K].first, T[p][K].second}); K++; } } } for (int r = 0; r < (int)R; r++) for (int c = 0; c < (int)C; c++) if (A[r][c] == p + 1) D[r][c] = dist[r][c]; } int main() { scanf("%d %d\n", &R, &C); scanf("%d\n", &P); for (int r = 0; r < (int)R; r++) for (int c = 0; c < (int)C; c++) { scanf("%d\n", &A[r][c]); T[A[r][c]].push_back({r, c}); D[r][c] = int(1e9); } for (int i = 0; i < (int)T[1].size(); i++) { int r = T[1][i].first; int c = T[1][i].second; D[r][c] = r + c; } for (int p = 1; p < (int)P; p++) { if (T[p].size() * T[p + 1].size() >= R * C) { bfs(p); } else { for (int i = 0; i < (int)T[p].size(); i++) { int r1 = T[p][i].first; int c1 = T[p][i].second; for (int j = 0; j < (int)T[p + 1].size(); j++) { int r2 = T[p + 1][j].first; int c2 = T[p + 1][j].second; D[r2][c2] = min(D[r2][c2], D[r1][c1] + abs(r1 - r2) + abs(c1 - c2)); } } } } printf("%d\n", D[T[P][0].first][T[P][0].second]); } ```
#include <bits/stdc++.h> using namespace std; int n, m, p; struct node { int x, y, dis; node(int _x, int _y, int _dis) { x = _x; y = _y; dis = _dis; } }; bool cmp(const node &a, const node &b) { return a.dis < b.dis; } void bfs(int k, vector<vector<pair<int, int> > > &pst, vector<vector<int> > &ans) { int g[n + 3][m + 3]; memset(g, 0, sizeof(g)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) g[i][j] = 10000000; vector<node> rq; for (int i = 0; i < pst[k - 1].size(); i++) { int x = pst[k - 1][i].first; int y = pst[k - 1][i].second; g[x][y] = ans[k - 1][i]; rq.push_back(node(x, y, ans[k - 1][i])); } sort(rq.begin(), rq.end(), cmp); queue<node> q; for (int i = 0; i < rq.size(); i++) { q.push(rq[i]); } bool flag[n + 3][m + 3]; memset(flag, 1, sizeof(flag)); int a[4], b[4]; a[0] = 0; a[1] = 1; a[2] = 0; a[3] = -1; b[0] = 1; b[1] = 0; b[2] = -1; b[3] = 0; while (!q.empty()) { node head = q.front(); int dis = g[head.x][head.y]; q.pop(); flag[head.x][head.y] = true; for (int i = 0; i < 4; i++) { int tx = head.x + a[i]; int ty = head.y + b[i]; if (tx <= 0 || tx > n || ty <= 0 || ty > m) continue; if (g[tx][ty] > dis + 1) { g[tx][ty] = dis + 1; if (flag[tx][ty]) { flag[tx][ty] = false; q.push(node(tx, ty, g[tx][ty])); } } } } for (int i = 0; i < pst[k].size(); i++) { ans[k][i] = g[pst[k][i].first][pst[k][i].second]; } } int main() { scanf("%d%d%d", &n, &m, &p); int g[310][310]; vector<vector<pair<int, int> > > pst(p + 1); vector<vector<int> > ans(p + 1); memset(g, 0, sizeof(g)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &g[i][j]); pst[g[i][j]].push_back(make_pair(i, j)); ans[g[i][j]].push_back(-1); } } for (int i = 0; i < pst[1].size(); i++) { ans[1][i] = pst[1][i].first + pst[1][i].second - 2; } for (int k = 2; k <= p; k++) { if (pst[k].size() * pst[k - 1].size() < 1000000) { for (int i = 0; i < pst[k].size(); i++) { for (int j = 0; j < pst[k - 1].size(); j++) { int dis = abs(pst[k][i].first - pst[k - 1][j].first) + abs(pst[k][i].second - pst[k - 1][j].second) + ans[k - 1][j]; if (ans[k][i] == -1) { ans[k][i] = dis; } else { ans[k][i] = min(ans[k][i], dis); } } } } else { bfs(k, pst, ans); } } printf("%d\n", ans[p][0]); 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 n, m, p; struct node { int x, y, dis; node(int _x, int _y, int _dis) { x = _x; y = _y; dis = _dis; } }; bool cmp(const node &a, const node &b) { return a.dis < b.dis; } void bfs(int k, vector<vector<pair<int, int> > > &pst, vector<vector<int> > &ans) { int g[n + 3][m + 3]; memset(g, 0, sizeof(g)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) g[i][j] = 10000000; vector<node> rq; for (int i = 0; i < pst[k - 1].size(); i++) { int x = pst[k - 1][i].first; int y = pst[k - 1][i].second; g[x][y] = ans[k - 1][i]; rq.push_back(node(x, y, ans[k - 1][i])); } sort(rq.begin(), rq.end(), cmp); queue<node> q; for (int i = 0; i < rq.size(); i++) { q.push(rq[i]); } bool flag[n + 3][m + 3]; memset(flag, 1, sizeof(flag)); int a[4], b[4]; a[0] = 0; a[1] = 1; a[2] = 0; a[3] = -1; b[0] = 1; b[1] = 0; b[2] = -1; b[3] = 0; while (!q.empty()) { node head = q.front(); int dis = g[head.x][head.y]; q.pop(); flag[head.x][head.y] = true; for (int i = 0; i < 4; i++) { int tx = head.x + a[i]; int ty = head.y + b[i]; if (tx <= 0 || tx > n || ty <= 0 || ty > m) continue; if (g[tx][ty] > dis + 1) { g[tx][ty] = dis + 1; if (flag[tx][ty]) { flag[tx][ty] = false; q.push(node(tx, ty, g[tx][ty])); } } } } for (int i = 0; i < pst[k].size(); i++) { ans[k][i] = g[pst[k][i].first][pst[k][i].second]; } } int main() { scanf("%d%d%d", &n, &m, &p); int g[310][310]; vector<vector<pair<int, int> > > pst(p + 1); vector<vector<int> > ans(p + 1); memset(g, 0, sizeof(g)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &g[i][j]); pst[g[i][j]].push_back(make_pair(i, j)); ans[g[i][j]].push_back(-1); } } for (int i = 0; i < pst[1].size(); i++) { ans[1][i] = pst[1][i].first + pst[1][i].second - 2; } for (int k = 2; k <= p; k++) { if (pst[k].size() * pst[k - 1].size() < 1000000) { for (int i = 0; i < pst[k].size(); i++) { for (int j = 0; j < pst[k - 1].size(); j++) { int dis = abs(pst[k][i].first - pst[k - 1][j].first) + abs(pst[k][i].second - pst[k - 1][j].second) + ans[k - 1][j]; if (ans[k][i] == -1) { ans[k][i] = dis; } else { ans[k][i] = min(ans[k][i], dis); } } } } else { bfs(k, pst, ans); } } printf("%d\n", ans[p][0]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 510; int n, m, k; int mov[4][2] = {1, 0, 0, 1, -1, 0, 0, -1}; int a[N][N], dis[N][N]; struct node { int x, y; int dis; }; vector<node> w[N * N]; void bfs(vector<node> &s) { vector<node> q; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) dis[i][j] = 1e9; int cnt = -1; q.push_back(s[++cnt]); for (int i = 0; i < q.size(); i++) { node v = q[i]; while (cnt + 1 < s.size() && s[cnt + 1].dis <= v.dis) q.push_back(s[++cnt]); for (int i = 0; i < 4; i++) { node u = {v.x + mov[i][0], v.y + mov[i][1]}; if (1 <= u.x && u.x <= n && 1 <= u.y && u.y <= m && v.dis + 1 < dis[u.x][u.y]) dis[u.x][u.y] = u.dis = v.dis + 1, q.push_back(u); } } } signed main() { scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf("%d", &a[i][j]), w[a[i][j]].push_back({i, j, a[i][j] == 1 ? i + j - 2 : (int)1e9}); for (int i = 2; i <= k; i++) { if (w[i - 1].size() * w[i].size() <= n * m) { for (node &u : w[i]) for (node v : w[i - 1]) u.dis = min(u.dis, v.dis + abs(u.x - v.x) + abs(u.y - v.y)); } else { vector<node> s; for (node v : w[i - 1]) s.push_back(v); bfs(s); for (node &u : w[i]) u.dis = dis[u.x][u.y]; } } printf("%d\n", w[k][0].dis); 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; const int N = 510; int n, m, k; int mov[4][2] = {1, 0, 0, 1, -1, 0, 0, -1}; int a[N][N], dis[N][N]; struct node { int x, y; int dis; }; vector<node> w[N * N]; void bfs(vector<node> &s) { vector<node> q; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) dis[i][j] = 1e9; int cnt = -1; q.push_back(s[++cnt]); for (int i = 0; i < q.size(); i++) { node v = q[i]; while (cnt + 1 < s.size() && s[cnt + 1].dis <= v.dis) q.push_back(s[++cnt]); for (int i = 0; i < 4; i++) { node u = {v.x + mov[i][0], v.y + mov[i][1]}; if (1 <= u.x && u.x <= n && 1 <= u.y && u.y <= m && v.dis + 1 < dis[u.x][u.y]) dis[u.x][u.y] = u.dis = v.dis + 1, q.push_back(u); } } } signed main() { scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf("%d", &a[i][j]), w[a[i][j]].push_back({i, j, a[i][j] == 1 ? i + j - 2 : (int)1e9}); for (int i = 2; i <= k; i++) { if (w[i - 1].size() * w[i].size() <= n * m) { for (node &u : w[i]) for (node v : w[i - 1]) u.dis = min(u.dis, v.dis + abs(u.x - v.x) + abs(u.y - v.y)); } else { vector<node> s; for (node v : w[i - 1]) s.push_back(v); bfs(s); for (node &u : w[i]) u.dis = dis[u.x][u.y]; } } printf("%d\n", w[k][0].dis); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 300 + 10; const int oo = 1 << 30; struct BitTree { int n, m, A[maxn][maxn]; void init(int a, int b) { n = a; m = b; for (int i = (1), _i = (n); i <= _i; i++) for (int j = (1), _j = (m); j <= _j; j++) A[i][j] = oo; } void add(int a, int b, int x) { for (int i = a; i <= n; i += (i & (-i))) for (int j = b; j <= m; j += (j & (-j))) A[i][j] = min(A[i][j], x); } void reset(int a, int b) { for (int i = a; i <= n; i += (i & (-i))) for (int j = b; j <= m; j += (j & (-j))) A[i][j] = oo; } int que(int a, int b) { int ret = oo; for (int i = a; i; i -= (i & (-i))) for (int j = b; j; j -= (j & (-j))) ret = min(ret, A[i][j]); return ret; } } LU, LD, RU, RD; struct Point { int x, y; Point() { x = y = 0; } Point(int a, int b) { x = a, y = b; } }; int A[maxn][maxn], F[maxn][maxn], N, M, P; vector<Point> ope[maxn * maxn]; int Done() { for (int i = (1), _i = (N); i <= _i; i++) for (int j = (1), _j = (M); j <= _j; j++) if (A[i][j] == 1) F[i][j] = i - 1 + j - 1; LU.init(N, M); LD.init(N, M); RU.init(N, M); RD.init(N, M); for (int i = (2), _i = (P); i <= _i; i++) { for (int j = (0), _j = (ope[i - 1].size() - 1); j <= _j; j++) { int x = ope[i - 1][j].x, y = ope[i - 1][j].y; LU.add(x, y, F[x][y] - x - y); LD.add(N - x + 1, y, F[x][y] + x - y); RU.add(x, M - y + 1, F[x][y] - x + y); RD.add(N - x + 1, M - y + 1, F[x][y] + x + y); } for (int j = (0), _j = (ope[i].size() - 1); j <= _j; j++) { int x = ope[i][j].x, y = ope[i][j].y; int ret = LU.que(x, y) + x + y; ret = min(ret, LD.que(N - x + 1, y) - x + y); ret = min(ret, RU.que(x, M - y + 1) + x - y); ret = min(ret, RD.que(N - x + 1, M - y + 1) - x - y); F[x][y] = ret; } for (int j = (0), _j = (ope[i - 1].size() - 1); j <= _j; j++) { int x = ope[i - 1][j].x, y = ope[i - 1][j].y; LU.reset(x, y); LD.reset(N - x + 1, y); RU.reset(x, M - y + 1); RD.reset(N - x + 1, M - y + 1); } } return F[ope[P][0].x][ope[P][0].y]; } int main(int argc, char* argv[]) { for (; scanf("%d%d%d", &N, &M, &P) != EOF;) { for (int i = (1), _i = (P); i <= _i; i++) ope[i].clear(); for (int i = (1), _i = (N); i <= _i; i++) for (int j = (1), _j = (M); j <= _j; j++) { scanf("%d", &A[i][j]); ope[A[i][j]].push_back(Point(i, j)); } printf("%d\n", Done()); } 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 maxn = 300 + 10; const int oo = 1 << 30; struct BitTree { int n, m, A[maxn][maxn]; void init(int a, int b) { n = a; m = b; for (int i = (1), _i = (n); i <= _i; i++) for (int j = (1), _j = (m); j <= _j; j++) A[i][j] = oo; } void add(int a, int b, int x) { for (int i = a; i <= n; i += (i & (-i))) for (int j = b; j <= m; j += (j & (-j))) A[i][j] = min(A[i][j], x); } void reset(int a, int b) { for (int i = a; i <= n; i += (i & (-i))) for (int j = b; j <= m; j += (j & (-j))) A[i][j] = oo; } int que(int a, int b) { int ret = oo; for (int i = a; i; i -= (i & (-i))) for (int j = b; j; j -= (j & (-j))) ret = min(ret, A[i][j]); return ret; } } LU, LD, RU, RD; struct Point { int x, y; Point() { x = y = 0; } Point(int a, int b) { x = a, y = b; } }; int A[maxn][maxn], F[maxn][maxn], N, M, P; vector<Point> ope[maxn * maxn]; int Done() { for (int i = (1), _i = (N); i <= _i; i++) for (int j = (1), _j = (M); j <= _j; j++) if (A[i][j] == 1) F[i][j] = i - 1 + j - 1; LU.init(N, M); LD.init(N, M); RU.init(N, M); RD.init(N, M); for (int i = (2), _i = (P); i <= _i; i++) { for (int j = (0), _j = (ope[i - 1].size() - 1); j <= _j; j++) { int x = ope[i - 1][j].x, y = ope[i - 1][j].y; LU.add(x, y, F[x][y] - x - y); LD.add(N - x + 1, y, F[x][y] + x - y); RU.add(x, M - y + 1, F[x][y] - x + y); RD.add(N - x + 1, M - y + 1, F[x][y] + x + y); } for (int j = (0), _j = (ope[i].size() - 1); j <= _j; j++) { int x = ope[i][j].x, y = ope[i][j].y; int ret = LU.que(x, y) + x + y; ret = min(ret, LD.que(N - x + 1, y) - x + y); ret = min(ret, RU.que(x, M - y + 1) + x - y); ret = min(ret, RD.que(N - x + 1, M - y + 1) - x - y); F[x][y] = ret; } for (int j = (0), _j = (ope[i - 1].size() - 1); j <= _j; j++) { int x = ope[i - 1][j].x, y = ope[i - 1][j].y; LU.reset(x, y); LD.reset(N - x + 1, y); RU.reset(x, M - y + 1); RD.reset(N - x + 1, M - y + 1); } } return F[ope[P][0].x][ope[P][0].y]; } int main(int argc, char* argv[]) { for (; scanf("%d%d%d", &N, &M, &P) != EOF;) { for (int i = (1), _i = (P); i <= _i; i++) ope[i].clear(); for (int i = (1), _i = (N); i <= _i; i++) for (int j = (1), _j = (M); j <= _j; j++) { scanf("%d", &A[i][j]); ope[A[i][j]].push_back(Point(i, j)); } printf("%d\n", Done()); } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int main() { ios::sync_with_stdio(0), cin.tie(0); int n, m; cin >> n >> m; int p; cin >> p; int a[n][m]; vector<pair<int, int>> v[p]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; a[i][j]--; v[a[i][j]].push_back({i, j}); } } int dis[n][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { dis[i][j] = INF; } } int vis[n][m]; memset(vis, 0, sizeof(vis)); priority_queue<pair<pair<int, int>, pair<int, int>>> pq; for (auto p : v[0]) { pq.push({{-(p.first + p.second), 0}, p}); dis[p.first][p.second] = 0; } vector<int> cnt(p); while (!pq.empty()) { int ux = pq.top().second.first; int uy = pq.top().second.second; int d = -pq.top().first.first; int idx = pq.top().first.second; pq.pop(); if (idx == p - 1) { cout << d << "\n"; return 0; } if (vis[ux][uy]) continue; vis[ux][uy] = 1; if (cnt[idx] > 5000) continue; cnt[idx]++; for (int i = 0; i < v[idx + 1].size(); ++i) { int vx = v[idx + 1][i].first, vy = v[idx + 1][i].second; int c = d + abs(vx - ux) + abs(vy - uy); if (dis[vx][vy] > c) { dis[vx][vy] = c; pq.push({{-dis[vx][vy], idx + 1}, {vx, vy}}); } } } 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 = 1e9; int main() { ios::sync_with_stdio(0), cin.tie(0); int n, m; cin >> n >> m; int p; cin >> p; int a[n][m]; vector<pair<int, int>> v[p]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; a[i][j]--; v[a[i][j]].push_back({i, j}); } } int dis[n][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { dis[i][j] = INF; } } int vis[n][m]; memset(vis, 0, sizeof(vis)); priority_queue<pair<pair<int, int>, pair<int, int>>> pq; for (auto p : v[0]) { pq.push({{-(p.first + p.second), 0}, p}); dis[p.first][p.second] = 0; } vector<int> cnt(p); while (!pq.empty()) { int ux = pq.top().second.first; int uy = pq.top().second.second; int d = -pq.top().first.first; int idx = pq.top().first.second; pq.pop(); if (idx == p - 1) { cout << d << "\n"; return 0; } if (vis[ux][uy]) continue; vis[ux][uy] = 1; if (cnt[idx] > 5000) continue; cnt[idx]++; for (int i = 0; i < v[idx + 1].size(); ++i) { int vx = v[idx + 1][i].first, vy = v[idx + 1][i].second; int c = d + abs(vx - ux) + abs(vy - uy); if (dis[vx][vy] > c) { dis[vx][vy] = c; pq.push({{-dis[vx][vy], idx + 1}, {vx, vy}}); } } } return 0; } ```
#include <bits/stdc++.h> using namespace std; struct POS { int x, y; POS(int x = 0, int y = 0) : x(x), y(y){}; }; vector<POS> s[90005]; int a[305][305]; int d[305][305]; bool vis[305][305]; int dp[305][305]; const int step[4][2] = {1, 0, 0, 1, -1, 0, 0, -1}; int get_distance(POS &a, POS &b) { return abs(a.x - b.x) + abs(a.y - b.y); } int main() { int n, m, p; while (~scanf("%d%d%d", &n, &m, &p)) { int x; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &a[i][j]); s[a[i][j]].push_back(POS(i, j)); } } memset(dp, 0x3f3f3f3f, sizeof(dp)); for (int i = 0; i < s[1].size(); ++i) { dp[s[1][i].x][s[1][i].y] = s[1][i].x + s[1][i].y - 2; } for (int i = 2; i <= p; ++i) { if (s[i].size() * s[i - 1].size() < n * m) { for (int j = 0; j < s[i].size(); ++j) { POS J = s[i][j]; for (int k = 0; k < s[i - 1].size(); ++k) { POS K = s[i - 1][k]; dp[J.x][J.y] = min(dp[K.x][K.y] + get_distance(J, K), dp[J.x][J.y]); } } } else { memset(d, 0x3f3f3f3f, sizeof(d)); memset(vis, 0, sizeof(vis)); queue<POS> Q; for (int j = 0; j < s[i - 1].size(); ++j) { POS J = s[i - 1][j]; Q.push(J); vis[J.x][J.y] = true; d[J.x][J.y] = dp[J.x][J.y]; } while (!Q.empty()) { POS u = Q.front(); Q.pop(); vis[u.x][u.y] = false; for (int j = 0; j < 4; ++j) { int x = u.x + step[j][0]; int y = u.y + step[j][1]; if (a[u.x][u.y] == i) dp[u.x][u.y] = min(dp[u.x][u.y], d[u.x][u.y]); if (x < 1 || x > n || y < 1 || y > m) continue; if (d[x][y] > d[u.x][u.y] + 1) { d[x][y] = d[u.x][u.y] + 1; if (!vis[x][y]) { vis[x][y] = true; if (a[x][y] == i) { dp[x][y] = min(dp[x][y], d[x][y]); } Q.push(POS(x, y)); } } } } } } POS K = s[p][0]; cout << dp[K.x][K.y] << endl; } }
### 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; struct POS { int x, y; POS(int x = 0, int y = 0) : x(x), y(y){}; }; vector<POS> s[90005]; int a[305][305]; int d[305][305]; bool vis[305][305]; int dp[305][305]; const int step[4][2] = {1, 0, 0, 1, -1, 0, 0, -1}; int get_distance(POS &a, POS &b) { return abs(a.x - b.x) + abs(a.y - b.y); } int main() { int n, m, p; while (~scanf("%d%d%d", &n, &m, &p)) { int x; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &a[i][j]); s[a[i][j]].push_back(POS(i, j)); } } memset(dp, 0x3f3f3f3f, sizeof(dp)); for (int i = 0; i < s[1].size(); ++i) { dp[s[1][i].x][s[1][i].y] = s[1][i].x + s[1][i].y - 2; } for (int i = 2; i <= p; ++i) { if (s[i].size() * s[i - 1].size() < n * m) { for (int j = 0; j < s[i].size(); ++j) { POS J = s[i][j]; for (int k = 0; k < s[i - 1].size(); ++k) { POS K = s[i - 1][k]; dp[J.x][J.y] = min(dp[K.x][K.y] + get_distance(J, K), dp[J.x][J.y]); } } } else { memset(d, 0x3f3f3f3f, sizeof(d)); memset(vis, 0, sizeof(vis)); queue<POS> Q; for (int j = 0; j < s[i - 1].size(); ++j) { POS J = s[i - 1][j]; Q.push(J); vis[J.x][J.y] = true; d[J.x][J.y] = dp[J.x][J.y]; } while (!Q.empty()) { POS u = Q.front(); Q.pop(); vis[u.x][u.y] = false; for (int j = 0; j < 4; ++j) { int x = u.x + step[j][0]; int y = u.y + step[j][1]; if (a[u.x][u.y] == i) dp[u.x][u.y] = min(dp[u.x][u.y], d[u.x][u.y]); if (x < 1 || x > n || y < 1 || y > m) continue; if (d[x][y] > d[u.x][u.y] + 1) { d[x][y] = d[u.x][u.y] + 1; if (!vis[x][y]) { vis[x][y] = true; if (a[x][y] == i) { dp[x][y] = min(dp[x][y], d[x][y]); } Q.push(POS(x, y)); } } } } } } POS K = s[p][0]; cout << dp[K.x][K.y] << endl; } } ```
#include <bits/stdc++.h> using namespace std; long long int cons; long long int check(long long int a) { if (a >= cons) a %= cons; return a; } long long int check2(long long int a) { if (a > 0) return a; long long int b = a / cons; a -= b * cons; if (a < 0) a += cons; return a; } long long int GCD(long long int a, long long int b) { if (b == 0) return a; return GCD(b, a % b); } long long int exp(long long int a, long long int n) { if (n == 0) return 1; if (n == 1) return check(a); long long int b = exp(a, n / 2); if (n % 2 == 0) return check(b * b); return check(b * check(b * a)); } int arr[301][301]; vector<pair<long long int, pair<long long int, long long int> > > color[10 * 100005 + 5]; long long int dp[301][301]; long long int dis(pair<long long int, long long int> a, pair<long long int, long long int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } void solve1(int n, int m, int cur, int prev) { int first = color[cur].size(); for (int i = 0; i < first; i++) { auto itr = color[cur][i]; long long int temp = 1e18; for (auto itr2 : color[prev]) { temp = min(temp, itr2.first + dis(itr.second, itr2.second)); } color[cur][i] = make_pair(temp, itr.second); } } bool in_queue[301][301]; long long int value; bool valid(int n, int m, int first, int second) { if (first < 1 || first > n || second < 1 || second > m) return false; return true; } long long int checker(int n, int m, int row, int col, queue<pair<int, int> > &q) { if (!valid(n, m, row, col)) return 1e18; if (in_queue[row][col]) return 1e18; in_queue[row][col] = true; q.push(make_pair(row, col)); dp[row][col] = value; return value; } void solve2(int n, int m, int cur, int prev) { queue<pair<int, int> > q; q.push(color[prev][0].second); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dp[i][j] = 1e18; in_queue[i][j] = false; } } dp[color[prev][0].second.first][color[prev][0].second.second] = color[prev][0].first; in_queue[color[prev][0].second.first][color[prev][0].second.second] = true; int ind = 1; int len = color[prev].size(); while (ind < len && color[prev][ind].first == color[prev][0].first) { q.push(color[prev][ind].second); dp[color[prev][ind].second.first][color[prev][ind].second.second] = color[prev][ind].first; in_queue[color[prev][ind].second.first][color[prev][ind].second.second] = true; ind++; } while (!q.empty()) { auto itr = q.front(); q.pop(); value = dp[itr.first][itr.second] + 1; long long int dd = checker(n, m, itr.first + 1, itr.second, q); dd = min(dd, checker(n, m, itr.first, itr.second + 1, q)); dd = min(dd, checker(n, m, itr.first - 1, itr.second, q)); dd = min(dd, checker(n, m, itr.first, itr.second - 1, q)); while (ind < len && (color[prev][ind].first <= value || q.empty())) { value = color[prev][ind].first; if (!in_queue[color[prev][ind].second.first] [color[prev][ind].second.second]) { q.push(color[prev][ind].second); in_queue[color[prev][ind].second.first] [color[prev][ind].second.second] = true; dp[color[prev][ind].second.first][color[prev][ind].second.second] = color[prev][ind].first; } ind++; } } int j = 0; for (auto itr : color[cur]) { color[cur][j] = make_pair(dp[itr.second.first][itr.second.second], itr.second); j++; } } int main() { ios::sync_with_stdio(false); cin.tie(0); cons = 1e9 + 7; int n, m, p; cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> arr[i][j]; color[arr[i][j]].push_back(make_pair(1e18, make_pair(i, j))); } } int first = color[1].size(); for (int i = 0; i < first; i++) { color[1][i].first = dis(color[1][i].second, make_pair(1, 1)); } for (int i = 2; i <= p; i++) { int len1 = color[i].size(); int len2 = color[i - 1].size(); if (len1 * len2 <= n * m) solve1(n, m, i, i - 1); else { sort(color[i - 1].begin(), color[i - 1].end()); solve2(n, m, i, i - 1); } } cout << color[p][0].first; }
### 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; long long int cons; long long int check(long long int a) { if (a >= cons) a %= cons; return a; } long long int check2(long long int a) { if (a > 0) return a; long long int b = a / cons; a -= b * cons; if (a < 0) a += cons; return a; } long long int GCD(long long int a, long long int b) { if (b == 0) return a; return GCD(b, a % b); } long long int exp(long long int a, long long int n) { if (n == 0) return 1; if (n == 1) return check(a); long long int b = exp(a, n / 2); if (n % 2 == 0) return check(b * b); return check(b * check(b * a)); } int arr[301][301]; vector<pair<long long int, pair<long long int, long long int> > > color[10 * 100005 + 5]; long long int dp[301][301]; long long int dis(pair<long long int, long long int> a, pair<long long int, long long int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } void solve1(int n, int m, int cur, int prev) { int first = color[cur].size(); for (int i = 0; i < first; i++) { auto itr = color[cur][i]; long long int temp = 1e18; for (auto itr2 : color[prev]) { temp = min(temp, itr2.first + dis(itr.second, itr2.second)); } color[cur][i] = make_pair(temp, itr.second); } } bool in_queue[301][301]; long long int value; bool valid(int n, int m, int first, int second) { if (first < 1 || first > n || second < 1 || second > m) return false; return true; } long long int checker(int n, int m, int row, int col, queue<pair<int, int> > &q) { if (!valid(n, m, row, col)) return 1e18; if (in_queue[row][col]) return 1e18; in_queue[row][col] = true; q.push(make_pair(row, col)); dp[row][col] = value; return value; } void solve2(int n, int m, int cur, int prev) { queue<pair<int, int> > q; q.push(color[prev][0].second); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dp[i][j] = 1e18; in_queue[i][j] = false; } } dp[color[prev][0].second.first][color[prev][0].second.second] = color[prev][0].first; in_queue[color[prev][0].second.first][color[prev][0].second.second] = true; int ind = 1; int len = color[prev].size(); while (ind < len && color[prev][ind].first == color[prev][0].first) { q.push(color[prev][ind].second); dp[color[prev][ind].second.first][color[prev][ind].second.second] = color[prev][ind].first; in_queue[color[prev][ind].second.first][color[prev][ind].second.second] = true; ind++; } while (!q.empty()) { auto itr = q.front(); q.pop(); value = dp[itr.first][itr.second] + 1; long long int dd = checker(n, m, itr.first + 1, itr.second, q); dd = min(dd, checker(n, m, itr.first, itr.second + 1, q)); dd = min(dd, checker(n, m, itr.first - 1, itr.second, q)); dd = min(dd, checker(n, m, itr.first, itr.second - 1, q)); while (ind < len && (color[prev][ind].first <= value || q.empty())) { value = color[prev][ind].first; if (!in_queue[color[prev][ind].second.first] [color[prev][ind].second.second]) { q.push(color[prev][ind].second); in_queue[color[prev][ind].second.first] [color[prev][ind].second.second] = true; dp[color[prev][ind].second.first][color[prev][ind].second.second] = color[prev][ind].first; } ind++; } } int j = 0; for (auto itr : color[cur]) { color[cur][j] = make_pair(dp[itr.second.first][itr.second.second], itr.second); j++; } } int main() { ios::sync_with_stdio(false); cin.tie(0); cons = 1e9 + 7; int n, m, p; cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> arr[i][j]; color[arr[i][j]].push_back(make_pair(1e18, make_pair(i, j))); } } int first = color[1].size(); for (int i = 0; i < first; i++) { color[1][i].first = dis(color[1][i].second, make_pair(1, 1)); } for (int i = 2; i <= p; i++) { int len1 = color[i].size(); int len2 = color[i - 1].size(); if (len1 * len2 <= n * m) solve1(n, m, i, i - 1); else { sort(color[i - 1].begin(), color[i - 1].end()); solve2(n, m, i, i - 1); } } cout << color[p][0].first; } ```
#include <bits/stdc++.h> using namespace std; int a[305][305] = {0}; struct node { int x, y; int d; }; vector<node> adj[301 * 301]; vector<int> row[301], col[301]; int dp[301][301] = {0}; int main() { int n, m, p, X, Y; node tmp; cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[i][j] = 1000000000; cin >> a[i][j]; tmp.x = i; tmp.y = j; if (a[i][j] == p) { X = i; Y = j; } adj[a[i][j]].push_back(tmp); } } for (int i = 0; i < adj[1].size(); i++) { dp[adj[1][i].x][adj[1][i].y] = adj[1][i].x + adj[1][i].y; } int cxup = 0, cxlow = 0, cylef = 0, cyri = 0, x, y, mid, an; for (int i = 2; i <= p; i++) { for (int j = 0; j < n; j++) row[j].clear(); for (int j = 0; j < m; j++) col[j].clear(); for (int j = 0; j < adj[i - 1].size(); j++) { row[adj[i - 1][j].x].push_back(adj[i - 1][j].y); } for (int j = 0; j < adj[i - 1].size(); j++) { col[adj[i - 1][j].y].push_back(adj[i - 1][j].x); } for (int j = 0; j < n; j++) { sort(row[j].begin(), row[j].end()); } for (int j = 0; j < m; j++) { sort(col[j].begin(), col[j].end()); } for (int j = 0; j < adj[i].size(); j++) { x = adj[i][j].x; y = adj[i][j].y; for (int k = 0; k < m; k++) if (col[k].size()) { mid = lower_bound(col[k].begin(), col[k].end(), x) - col[k].begin(); if (mid == col[k].size()) { an = col[k][mid - 1]; dp[x][y] = min(dp[x][y], dp[an][k] + abs(x - an) + abs(y - k)); } else if (mid == 0) { an = col[k][mid]; dp[x][y] = min(dp[x][y], dp[an][k] + abs(x - an) + abs(y - k)); } else { an = col[k][mid - 1]; dp[x][y] = min(dp[x][y], dp[an][k] + abs(x - an) + abs(y - k)); an = col[k][mid]; dp[x][y] = min(dp[x][y], dp[an][k] + abs(x - an) + abs(y - k)); } } for (int k = 0; k < n; k++) if (row[k].size()) { mid = lower_bound(row[k].begin(), row[k].end(), y) - row[k].begin(); if (mid == row[k].size()) { an = row[k][mid - 1]; dp[x][y] = min(dp[x][y], dp[k][an] + abs(x - k) + abs(y - an)); } else if (mid == 0) { an = row[k][mid]; dp[x][y] = min(dp[x][y], dp[k][an] + abs(x - k) + abs(y - an)); } else { an = row[k][mid - 1]; dp[x][y] = min(dp[x][y], dp[k][an] + abs(x - k) + abs(y - an)); an = row[k][mid]; dp[x][y] = min(dp[x][y], dp[k][an] + abs(x - k) + abs(y - an)); } } } } cout << dp[X][Y] << endl; }
### 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 a[305][305] = {0}; struct node { int x, y; int d; }; vector<node> adj[301 * 301]; vector<int> row[301], col[301]; int dp[301][301] = {0}; int main() { int n, m, p, X, Y; node tmp; cin >> n >> m >> p; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[i][j] = 1000000000; cin >> a[i][j]; tmp.x = i; tmp.y = j; if (a[i][j] == p) { X = i; Y = j; } adj[a[i][j]].push_back(tmp); } } for (int i = 0; i < adj[1].size(); i++) { dp[adj[1][i].x][adj[1][i].y] = adj[1][i].x + adj[1][i].y; } int cxup = 0, cxlow = 0, cylef = 0, cyri = 0, x, y, mid, an; for (int i = 2; i <= p; i++) { for (int j = 0; j < n; j++) row[j].clear(); for (int j = 0; j < m; j++) col[j].clear(); for (int j = 0; j < adj[i - 1].size(); j++) { row[adj[i - 1][j].x].push_back(adj[i - 1][j].y); } for (int j = 0; j < adj[i - 1].size(); j++) { col[adj[i - 1][j].y].push_back(adj[i - 1][j].x); } for (int j = 0; j < n; j++) { sort(row[j].begin(), row[j].end()); } for (int j = 0; j < m; j++) { sort(col[j].begin(), col[j].end()); } for (int j = 0; j < adj[i].size(); j++) { x = adj[i][j].x; y = adj[i][j].y; for (int k = 0; k < m; k++) if (col[k].size()) { mid = lower_bound(col[k].begin(), col[k].end(), x) - col[k].begin(); if (mid == col[k].size()) { an = col[k][mid - 1]; dp[x][y] = min(dp[x][y], dp[an][k] + abs(x - an) + abs(y - k)); } else if (mid == 0) { an = col[k][mid]; dp[x][y] = min(dp[x][y], dp[an][k] + abs(x - an) + abs(y - k)); } else { an = col[k][mid - 1]; dp[x][y] = min(dp[x][y], dp[an][k] + abs(x - an) + abs(y - k)); an = col[k][mid]; dp[x][y] = min(dp[x][y], dp[an][k] + abs(x - an) + abs(y - k)); } } for (int k = 0; k < n; k++) if (row[k].size()) { mid = lower_bound(row[k].begin(), row[k].end(), y) - row[k].begin(); if (mid == row[k].size()) { an = row[k][mid - 1]; dp[x][y] = min(dp[x][y], dp[k][an] + abs(x - k) + abs(y - an)); } else if (mid == 0) { an = row[k][mid]; dp[x][y] = min(dp[x][y], dp[k][an] + abs(x - k) + abs(y - an)); } else { an = row[k][mid - 1]; dp[x][y] = min(dp[x][y], dp[k][an] + abs(x - k) + abs(y - an)); an = row[k][mid]; dp[x][y] = min(dp[x][y], dp[k][an] + abs(x - k) + abs(y - an)); } } } } cout << dp[X][Y] << endl; } ```
#include <bits/stdc++.h> using namespace std; struct node { int x, y, times; }; int T, t, n, m, P, INF = 1e9; int val[310][310]; long long num[90010]; vector<node> vc[90010]; int _x[4] = {0, 1, 0, -1}, _y[4] = {-1, 0, 1, 0}; int vis[310][310]; vector<node> vc2[610]; void bfs(int K) { int i, j, k, k2, x, y, x2, y2, minn = 1e9, ret, len; node A; memset(vis, -1, sizeof(vis)); for (i = 0; i <= 605; i++) vc2[i].clear(); for (i = 0; i < num[K]; i++) minn = min(minn, vc[K][i].times); for (i = 0; i < num[K]; i++) { ret = vc[K][i].times - minn; if (ret <= 600) vc2[ret].push_back(vc[K][i]); } for (k = 0; k <= 600; k++) { len = vc2[k].size(); for (i = 0; i < len; i++) { x = vc2[k][i].x; y = vc2[k][i].y; vis[x][y] = minn + k; for (k2 = 0; k2 < 4; k2++) { x2 = x + _x[k2]; y2 = y + _y[k2]; if (1 <= x2 && x2 <= n && 1 <= y2 && y2 <= m && vis[x2][y2] == -1) { vis[x2][y2] = minn + k + 1; A.x = x2; A.y = y2; vc2[k + 1].push_back(A); } } } } } int main() { int i, j, k, ans; node A; scanf("%d%d%d", &n, &m, &P); A.times = 1e9; for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { scanf("%d", &val[i][j]); A.x = i; A.y = j; vc[val[i][j]].push_back(A); } A.x = 1; A.y = 1; A.times = 0; vc[0].push_back(A); for (i = 0; i <= P; i++) num[i] = vc[i].size(); for (k = 0; k < P; k++) { if (num[k] * num[k + 1] <= 90000) { for (i = 0; i < num[k]; i++) for (j = 0; j < num[k + 1]; j++) { vc[k + 1][j].times = min(vc[k + 1][j].times, vc[k][i].times + abs(vc[k][i].x - vc[k + 1][j].x) + abs(vc[k][i].y - vc[k + 1][j].y)); } } else { bfs(k); for (j = 0; j < num[k + 1]; j++) vc[k + 1][j].times = vis[vc[k + 1][j].x][vc[k + 1][j].y]; } } ans = 1e9; for (i = 0; i < num[P]; i++) ans = min(ans, vc[P][i].times); printf("%d\n", ans); }
### 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; struct node { int x, y, times; }; int T, t, n, m, P, INF = 1e9; int val[310][310]; long long num[90010]; vector<node> vc[90010]; int _x[4] = {0, 1, 0, -1}, _y[4] = {-1, 0, 1, 0}; int vis[310][310]; vector<node> vc2[610]; void bfs(int K) { int i, j, k, k2, x, y, x2, y2, minn = 1e9, ret, len; node A; memset(vis, -1, sizeof(vis)); for (i = 0; i <= 605; i++) vc2[i].clear(); for (i = 0; i < num[K]; i++) minn = min(minn, vc[K][i].times); for (i = 0; i < num[K]; i++) { ret = vc[K][i].times - minn; if (ret <= 600) vc2[ret].push_back(vc[K][i]); } for (k = 0; k <= 600; k++) { len = vc2[k].size(); for (i = 0; i < len; i++) { x = vc2[k][i].x; y = vc2[k][i].y; vis[x][y] = minn + k; for (k2 = 0; k2 < 4; k2++) { x2 = x + _x[k2]; y2 = y + _y[k2]; if (1 <= x2 && x2 <= n && 1 <= y2 && y2 <= m && vis[x2][y2] == -1) { vis[x2][y2] = minn + k + 1; A.x = x2; A.y = y2; vc2[k + 1].push_back(A); } } } } } int main() { int i, j, k, ans; node A; scanf("%d%d%d", &n, &m, &P); A.times = 1e9; for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { scanf("%d", &val[i][j]); A.x = i; A.y = j; vc[val[i][j]].push_back(A); } A.x = 1; A.y = 1; A.times = 0; vc[0].push_back(A); for (i = 0; i <= P; i++) num[i] = vc[i].size(); for (k = 0; k < P; k++) { if (num[k] * num[k + 1] <= 90000) { for (i = 0; i < num[k]; i++) for (j = 0; j < num[k + 1]; j++) { vc[k + 1][j].times = min(vc[k + 1][j].times, vc[k][i].times + abs(vc[k][i].x - vc[k + 1][j].x) + abs(vc[k][i].y - vc[k + 1][j].y)); } } else { bfs(k); for (j = 0; j < num[k + 1]; j++) vc[k + 1][j].times = vis[vc[k + 1][j].x][vc[k + 1][j].y]; } } ans = 1e9; for (i = 0; i < num[P]; i++) ans = min(ans, vc[P][i].times); printf("%d\n", ans); } ```
#include <bits/stdc++.h> using namespace std; int n, m, p, a[505][505], dp[505][505], d[505][505]; vector<pair<int, int> > indi[250505]; vector<pair<int, pair<int, int> > > bfs, lst; int fx, fy; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; 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); } int i, j, k; 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]); indi[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 cursize = indi[i].size(); int last = indi[i - 1].size(); if (cursize * last <= n * m) { for (j = 0; j < cursize; j++) { int curx = indi[i][j].first; int cury = indi[i][j].second; for (k = 0; k < last; k++) { int last_x = indi[i - 1][k].first; int last_y = indi[i - 1][k].second; dp[curx][cury] = min(dp[curx][cury], dp[last_x][last_y] + find_dist(curx, cury, 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; j++) { int last_x = indi[i - 1][j].first; int last_y = indi[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()); bfs.push_back(lst[0]); int pointer = 1; j = 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 < cursize; j++) { int x = indi[i][j].first; int y = indi[i][j].second; dp[x][y] = d[x][y]; } } } cout << dp[fx][fy] << 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, a[505][505], dp[505][505], d[505][505]; vector<pair<int, int> > indi[250505]; vector<pair<int, pair<int, int> > > bfs, lst; int fx, fy; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; 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); } int i, j, k; 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]); indi[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 cursize = indi[i].size(); int last = indi[i - 1].size(); if (cursize * last <= n * m) { for (j = 0; j < cursize; j++) { int curx = indi[i][j].first; int cury = indi[i][j].second; for (k = 0; k < last; k++) { int last_x = indi[i - 1][k].first; int last_y = indi[i - 1][k].second; dp[curx][cury] = min(dp[curx][cury], dp[last_x][last_y] + find_dist(curx, cury, 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; j++) { int last_x = indi[i - 1][j].first; int last_y = indi[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()); bfs.push_back(lst[0]); int pointer = 1; j = 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 < cursize; j++) { int x = indi[i][j].first; int y = indi[i][j].second; dp[x][y] = d[x][y]; } } } cout << dp[fx][fy] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 7; int mp[305][305]; int dp[305][305]; bool vis[305][305]; int ddx[4] = {1, -1, 0, 0}; int ddy[4] = {0, 0, 1, -1}; vector<pair<int, int> > v[305 * 305]; int pos; const bool cmp(const pair<int, int>& a, const pair<int, int>& b) { int x1 = a.first; int y1 = a.second; int x2 = b.first; int y2 = b.second; return dp[x1][y1] < dp[x2][y2]; } struct node { int x, y; int dis; node(int _x, int _y, int _dis) : x(_x), y(_y), dis(_dis){}; }; queue<node> q; int main() { int m, n, p, f; while (scanf("%d%d%d", &n, &m, &p) != EOF) { for (int i = 0; i < p; i++) v[i].clear(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &mp[i][j]); v[mp[i][j]].push_back(make_pair(i, j)); dp[i][j] = inf; } } for (int i = 0; i < v[1].size(); i++) { int x = v[1][i].first; int y = v[1][i].second; dp[x][y] = x + y - 2; } for (int i = 2; i <= p; i++) { int cnt = v[i].size() * v[i - 1].size(); sort(v[i - 1].begin(), v[i - 1].end(), cmp); if (cnt < n * m) { for (int j = 0; j < v[i].size(); j++) { int x = v[i][j].first; int y = v[i][j].second; for (int k = 0; k < v[i - 1].size(); k++) { int dx = v[i - 1][k].first; int dy = v[i - 1][k].second; if (dp[dx][dy] >= dp[x][y]) break; dp[x][y] = min(dp[x][y], dp[dx][dy] + abs(dx - x) + abs(dy - y)); } } } else { while (!q.empty()) q.pop(); memset(vis, 0, sizeof(vis)); int x = v[i - 1][0].first; int y = v[i - 1][0].second; node tmp(x, y, dp[x][y]); vis[x][y] = 1; q.push(tmp); int now = 1; while (!q.empty()) { tmp = q.front(); q.pop(); while (now < v[i - 1].size()) { int tx = v[i - 1][now].first; int ty = v[i - 1][now].second; if (dp[tx][ty] > tmp.dis) break; q.push(node(tx, ty, dp[tx][ty])); vis[tx][ty] = 1; now++; } for (int j = 0; j < 4; j++) { int nx = tmp.x + ddx[j]; int ny = tmp.y + ddy[j]; if (nx < 1 || nx > n || ny < 1 || ny > m || vis[nx][ny]) continue; vis[nx][ny] = 1; if (mp[nx][ny] == i) dp[nx][ny] = tmp.dis + 1; q.push(node(nx, ny, tmp.dis + 1)); } } } } int x = v[p][0].first; int y = v[p][0].second; printf("%d", dp[x][y]); } 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 + 7; int mp[305][305]; int dp[305][305]; bool vis[305][305]; int ddx[4] = {1, -1, 0, 0}; int ddy[4] = {0, 0, 1, -1}; vector<pair<int, int> > v[305 * 305]; int pos; const bool cmp(const pair<int, int>& a, const pair<int, int>& b) { int x1 = a.first; int y1 = a.second; int x2 = b.first; int y2 = b.second; return dp[x1][y1] < dp[x2][y2]; } struct node { int x, y; int dis; node(int _x, int _y, int _dis) : x(_x), y(_y), dis(_dis){}; }; queue<node> q; int main() { int m, n, p, f; while (scanf("%d%d%d", &n, &m, &p) != EOF) { for (int i = 0; i < p; i++) v[i].clear(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &mp[i][j]); v[mp[i][j]].push_back(make_pair(i, j)); dp[i][j] = inf; } } for (int i = 0; i < v[1].size(); i++) { int x = v[1][i].first; int y = v[1][i].second; dp[x][y] = x + y - 2; } for (int i = 2; i <= p; i++) { int cnt = v[i].size() * v[i - 1].size(); sort(v[i - 1].begin(), v[i - 1].end(), cmp); if (cnt < n * m) { for (int j = 0; j < v[i].size(); j++) { int x = v[i][j].first; int y = v[i][j].second; for (int k = 0; k < v[i - 1].size(); k++) { int dx = v[i - 1][k].first; int dy = v[i - 1][k].second; if (dp[dx][dy] >= dp[x][y]) break; dp[x][y] = min(dp[x][y], dp[dx][dy] + abs(dx - x) + abs(dy - y)); } } } else { while (!q.empty()) q.pop(); memset(vis, 0, sizeof(vis)); int x = v[i - 1][0].first; int y = v[i - 1][0].second; node tmp(x, y, dp[x][y]); vis[x][y] = 1; q.push(tmp); int now = 1; while (!q.empty()) { tmp = q.front(); q.pop(); while (now < v[i - 1].size()) { int tx = v[i - 1][now].first; int ty = v[i - 1][now].second; if (dp[tx][ty] > tmp.dis) break; q.push(node(tx, ty, dp[tx][ty])); vis[tx][ty] = 1; now++; } for (int j = 0; j < 4; j++) { int nx = tmp.x + ddx[j]; int ny = tmp.y + ddy[j]; if (nx < 1 || nx > n || ny < 1 || ny > m || vis[nx][ny]) continue; vis[nx][ny] = 1; if (mp[nx][ny] == i) dp[nx][ny] = tmp.dis + 1; q.push(node(nx, ny, tmp.dis + 1)); } } } } int x = v[p][0].first; int y = v[p][0].second; printf("%d", dp[x][y]); } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 3e2 + 10; int n, m, p, a[maxn][maxn]; int dp[maxn][maxn], dis[maxn][maxn]; queue<pair<int, int> > q; vector<pair<int, int> > vc[maxn * maxn], temp[2]; bool cmp(pair<int, int> x, pair<int, int> y) { return dp[x.first][x.second] < dp[y.first][y.second]; } bool vis[maxn][maxn]; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; void bfs(int c, int nc) { while (q.size()) q.pop(); memset(dis, 0x3f, sizeof dis); memset(vis, 0, sizeof vis); sort(vc[c].begin(), vc[c].end(), cmp); for (auto it : vc[c]) dis[it.first][it.second] = dp[it.first][it.second]; pair<int, int> it = vc[c][0]; dis[it.first][it.second] = dp[it.first][it.second]; vis[it.first][it.second] = 1; q.push(it); int sz = vc[c].size(); int pos = 1; while (q.size() || pos < sz) { if (pos < sz) while (vis[vc[c][pos].first][vc[c][pos].second] && pos < sz) pos++; if (q.size() == 0 && pos < sz) q.push(vc[c][pos++]), vis[vc[c][pos - 1].first][vc[c][pos - 1].second] = 1; if (q.size() == 0) break; int x = q.front().first, y = q.front().second; q.pop(); while (pos < sz) { if (dis[x][y] >= dis[vc[c][pos].first][vc[c][pos].second] - 1) { if (!vis[vc[c][pos].first][vc[c][pos].second]) q.push(vc[c][pos]), vis[vc[c][pos].first][vc[c][pos].second] = 1; pos++; } else break; } for (int i = 0; i < 4; i++) { int nx = dx[i] + x, ny = dy[i] + y; if (nx > n || nx < 1 || ny > m || ny < 1) continue; if (!vis[nx][ny]) { dis[nx][ny] = min(dis[nx][ny], dis[x][y] + 1); vis[nx][ny] = 1; q.push({nx, ny}); } } } for (auto it : vc[nc]) dp[it.first][it.second] = dis[it.first][it.second]; } int main() { scanf("%d %d %d", &n, &m, &p); memset(dp, 0x3f, sizeof dp); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); vc[a[i][j]].push_back({i, j}); } temp[0].clear(); temp[0].push_back({1, 1}); temp[1] = vc[1]; for (auto i : temp[0]) for (auto j : temp[1]) { int x1 = i.first, y1 = i.second; int x2 = j.first, y2 = j.second; dp[x2][y2] = min(dp[x2][y2], abs(x2 - x1) + abs(y2 - y1)); } for (int c = 1; c < p; c++) { int nc = c + 1; if ((int)vc[c].size() * (int)vc[nc].size() >= n * m) { bfs(c, nc); continue; } temp[0] = vc[c]; temp[1] = vc[nc]; for (auto i : temp[0]) for (auto j : temp[1]) { int x1 = i.first, y1 = i.second; int x2 = j.first, y2 = j.second; dp[x2][y2] = min(dp[x2][y2], dp[x1][y1] + abs(x2 - x1) + abs(y2 - y1)); } } int ans = INT_MAX; for (auto it : vc[p]) ans = min(ans, dp[it.first][it.second]); 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; const int maxn = 3e2 + 10; int n, m, p, a[maxn][maxn]; int dp[maxn][maxn], dis[maxn][maxn]; queue<pair<int, int> > q; vector<pair<int, int> > vc[maxn * maxn], temp[2]; bool cmp(pair<int, int> x, pair<int, int> y) { return dp[x.first][x.second] < dp[y.first][y.second]; } bool vis[maxn][maxn]; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; void bfs(int c, int nc) { while (q.size()) q.pop(); memset(dis, 0x3f, sizeof dis); memset(vis, 0, sizeof vis); sort(vc[c].begin(), vc[c].end(), cmp); for (auto it : vc[c]) dis[it.first][it.second] = dp[it.first][it.second]; pair<int, int> it = vc[c][0]; dis[it.first][it.second] = dp[it.first][it.second]; vis[it.first][it.second] = 1; q.push(it); int sz = vc[c].size(); int pos = 1; while (q.size() || pos < sz) { if (pos < sz) while (vis[vc[c][pos].first][vc[c][pos].second] && pos < sz) pos++; if (q.size() == 0 && pos < sz) q.push(vc[c][pos++]), vis[vc[c][pos - 1].first][vc[c][pos - 1].second] = 1; if (q.size() == 0) break; int x = q.front().first, y = q.front().second; q.pop(); while (pos < sz) { if (dis[x][y] >= dis[vc[c][pos].first][vc[c][pos].second] - 1) { if (!vis[vc[c][pos].first][vc[c][pos].second]) q.push(vc[c][pos]), vis[vc[c][pos].first][vc[c][pos].second] = 1; pos++; } else break; } for (int i = 0; i < 4; i++) { int nx = dx[i] + x, ny = dy[i] + y; if (nx > n || nx < 1 || ny > m || ny < 1) continue; if (!vis[nx][ny]) { dis[nx][ny] = min(dis[nx][ny], dis[x][y] + 1); vis[nx][ny] = 1; q.push({nx, ny}); } } } for (auto it : vc[nc]) dp[it.first][it.second] = dis[it.first][it.second]; } int main() { scanf("%d %d %d", &n, &m, &p); memset(dp, 0x3f, sizeof dp); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); vc[a[i][j]].push_back({i, j}); } temp[0].clear(); temp[0].push_back({1, 1}); temp[1] = vc[1]; for (auto i : temp[0]) for (auto j : temp[1]) { int x1 = i.first, y1 = i.second; int x2 = j.first, y2 = j.second; dp[x2][y2] = min(dp[x2][y2], abs(x2 - x1) + abs(y2 - y1)); } for (int c = 1; c < p; c++) { int nc = c + 1; if ((int)vc[c].size() * (int)vc[nc].size() >= n * m) { bfs(c, nc); continue; } temp[0] = vc[c]; temp[1] = vc[nc]; for (auto i : temp[0]) for (auto j : temp[1]) { int x1 = i.first, y1 = i.second; int x2 = j.first, y2 = j.second; dp[x2][y2] = min(dp[x2][y2], dp[x1][y1] + abs(x2 - x1) + abs(y2 - y1)); } } int ans = INT_MAX; for (auto it : vc[p]) ans = min(ans, dp[it.first][it.second]); printf("%d\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; int n, m, p; int dist[90055]; vector<int> vec[90055]; int main() { scanf("%d %d %d", &n, &m, &p); int x; vec[0].emplace_back(0); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &x); vec[x].emplace_back(i * m + j); } } memset(dist, 63, sizeof(dist)); dist[0] = 0; for (int level = 0; level < p; level++) { if (level == 1 && find(vec[1].begin(), vec[1].end(), 0) == vec[1].end()) dist[0] = (int)1e9; if (vec[level + 1].size() * vec[level].size() <= 90000) { for (auto u : vec[level]) { int x = u / m, y = u % m; for (auto v : vec[level + 1]) { int nx = v / m, ny = v % m; dist[v] = min(dist[v], dist[u] + abs(x - nx) + abs(y - ny)); } } continue; } vector<bool> in_que(n * m, false); vector<int> d(n * m, (int)1e9); queue<int> que; for (auto u : vec[level]) { d[u] = dist[u]; que.push(u); } while (!que.empty()) { int u = que.front(); que.pop(); in_que[u] = false; int x = u / m, y = u % m; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; int v = nx * m + ny, w = abs(nx - x) + abs(ny - y); if (nx >= 0 && nx < n && ny >= 0 && ny < m && d[v] > d[u] + w) { d[v] = d[u] + w; if (!in_que[v]) { in_que[v] = true; que.push(v); } } } } for (auto u : vec[level + 1]) dist[u] = d[u]; } int res = INT_MAX; for (auto u : vec[p]) res = min(res, dist[u]); printf("%d\n", res); 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 dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; int n, m, p; int dist[90055]; vector<int> vec[90055]; int main() { scanf("%d %d %d", &n, &m, &p); int x; vec[0].emplace_back(0); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &x); vec[x].emplace_back(i * m + j); } } memset(dist, 63, sizeof(dist)); dist[0] = 0; for (int level = 0; level < p; level++) { if (level == 1 && find(vec[1].begin(), vec[1].end(), 0) == vec[1].end()) dist[0] = (int)1e9; if (vec[level + 1].size() * vec[level].size() <= 90000) { for (auto u : vec[level]) { int x = u / m, y = u % m; for (auto v : vec[level + 1]) { int nx = v / m, ny = v % m; dist[v] = min(dist[v], dist[u] + abs(x - nx) + abs(y - ny)); } } continue; } vector<bool> in_que(n * m, false); vector<int> d(n * m, (int)1e9); queue<int> que; for (auto u : vec[level]) { d[u] = dist[u]; que.push(u); } while (!que.empty()) { int u = que.front(); que.pop(); in_que[u] = false; int x = u / m, y = u % m; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; int v = nx * m + ny, w = abs(nx - x) + abs(ny - y); if (nx >= 0 && nx < n && ny >= 0 && ny < m && d[v] > d[u] + w) { d[v] = d[u] + w; if (!in_que[v]) { in_que[v] = true; que.push(v); } } } } for (auto u : vec[level + 1]) dist[u] = d[u]; } int res = INT_MAX; for (auto u : vec[p]) res = min(res, dist[u]); printf("%d\n", res); return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p; int chest[305][305]; vector<pair<int, int> > record[90005]; long long dp[305][305]; int xp, yp; void input() { scanf("%d %d %d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &chest[i][j]); if (chest[i][j] == p) { xp = i; yp = j; } } } int dist(int x1, int y1, int x2, int y2) { return abs(x2 - x1) + abs(y2 - y1); } void build() { int cur = 1; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { record[chest[i][j]].push_back(make_pair(i, j)); } } struct node { int r, c; int ind; int cost; }; long long cost[305][305]; class mycomp { public: bool operator()(const node& l, const node& r) const { return l.cost > r.cost; } }; void bfs(int color) { queue<node> q; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cost[i][j] = 1000000000; for (int i = 0; i < record[color].size(); i++) { pair<int, int> p1 = record[color][i]; node temp; temp.r = p1.first, temp.c = p1.second, temp.ind = i; cost[temp.r][temp.c] = dp[p1.first][p1.second]; q.push(temp); } int dr[] = {-1, 1, 0, 0}; int dc[] = {0, 0, -1, 1}; while (!q.empty()) { node top = q.front(); q.pop(); for (int i = 0; i < 4; i++) { int rr = top.r + dr[i]; int cc = top.c + dc[i]; if (rr > n || rr <= 0 || cc > m || cc <= 0) continue; if (cost[rr][cc] > cost[top.r][top.c] + 1) { cost[rr][cc] = cost[top.r][top.c] + 1; node temp; temp.r = rr, temp.c = cc, temp.ind = top.ind; q.push(temp); } } } for (int i = 0; i < record[color + 1].size(); i++) { pair<int, int> p1 = record[color + 1][i]; dp[p1.first][p1.second] = cost[p1.first][p1.second]; } } void solve() { for (int i = 0; i < record[1].size(); i++) { pair<int, int> p1 = record[1][i]; dp[p1.first][p1.second] = dist(1, 1, p1.first, p1.second); } for (int i = 2; i <= p; i++) { if (record[i].size() * record[i - 1].size() >= n * m) { bfs(i - 1); continue; } for (int j = 0; j < record[i].size(); j++) { long long ans = 1000000000; pair<int, int> p1 = record[i][j]; for (int k = 0; k < record[i - 1].size(); k++) { pair<int, int> p2 = record[i - 1][k]; ans = min(ans, (long long)dist(p1.first, p1.second, p2.first, p2.second) + dp[p2.first][p2.second]); } dp[p1.first][p1.second] = ans; } } cout << dp[xp][yp] << endl; } int main() { input(); build(); solve(); }
### 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 chest[305][305]; vector<pair<int, int> > record[90005]; long long dp[305][305]; int xp, yp; void input() { scanf("%d %d %d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &chest[i][j]); if (chest[i][j] == p) { xp = i; yp = j; } } } int dist(int x1, int y1, int x2, int y2) { return abs(x2 - x1) + abs(y2 - y1); } void build() { int cur = 1; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { record[chest[i][j]].push_back(make_pair(i, j)); } } struct node { int r, c; int ind; int cost; }; long long cost[305][305]; class mycomp { public: bool operator()(const node& l, const node& r) const { return l.cost > r.cost; } }; void bfs(int color) { queue<node> q; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cost[i][j] = 1000000000; for (int i = 0; i < record[color].size(); i++) { pair<int, int> p1 = record[color][i]; node temp; temp.r = p1.first, temp.c = p1.second, temp.ind = i; cost[temp.r][temp.c] = dp[p1.first][p1.second]; q.push(temp); } int dr[] = {-1, 1, 0, 0}; int dc[] = {0, 0, -1, 1}; while (!q.empty()) { node top = q.front(); q.pop(); for (int i = 0; i < 4; i++) { int rr = top.r + dr[i]; int cc = top.c + dc[i]; if (rr > n || rr <= 0 || cc > m || cc <= 0) continue; if (cost[rr][cc] > cost[top.r][top.c] + 1) { cost[rr][cc] = cost[top.r][top.c] + 1; node temp; temp.r = rr, temp.c = cc, temp.ind = top.ind; q.push(temp); } } } for (int i = 0; i < record[color + 1].size(); i++) { pair<int, int> p1 = record[color + 1][i]; dp[p1.first][p1.second] = cost[p1.first][p1.second]; } } void solve() { for (int i = 0; i < record[1].size(); i++) { pair<int, int> p1 = record[1][i]; dp[p1.first][p1.second] = dist(1, 1, p1.first, p1.second); } for (int i = 2; i <= p; i++) { if (record[i].size() * record[i - 1].size() >= n * m) { bfs(i - 1); continue; } for (int j = 0; j < record[i].size(); j++) { long long ans = 1000000000; pair<int, int> p1 = record[i][j]; for (int k = 0; k < record[i - 1].size(); k++) { pair<int, int> p2 = record[i - 1][k]; ans = min(ans, (long long)dist(p1.first, p1.second, p2.first, p2.second) + dp[p2.first][p2.second]); } dp[p1.first][p1.second] = ans; } } cout << dp[xp][yp] << endl; } int main() { input(); build(); solve(); } ```
#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> f[309 * 309]; 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), f[x].push_back({i, j, (int)1e9}); f[0].push_back({0, 0, 0}); for (int i = 0; i < p; i++) { sort(f[i].begin(), f[i].end()); for (int j = 0; j < min((int)f[i].size(), 600); j++) for (auto &k : f[i + 1]) { k.v = min(k.v, f[i][j].v + abs(f[i][j].x - k.x) + abs(f[i][j].y - k.y)); if (i == p - 1) ans = min(ans, k.v); } } printf("%d", ans); }
### 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> f[309 * 309]; 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), f[x].push_back({i, j, (int)1e9}); f[0].push_back({0, 0, 0}); for (int i = 0; i < p; i++) { sort(f[i].begin(), f[i].end()); for (int j = 0; j < min((int)f[i].size(), 600); j++) for (auto &k : f[i + 1]) { k.v = min(k.v, f[i][j].v + abs(f[i][j].x - k.x) + abs(f[i][j].y - k.y)); if (i == p - 1) ans = min(ans, k.v); } } printf("%d", ans); } ```
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0; char ch = getchar(); bool f = 0; for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = 1; for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0'; return f ? -x : x; } void write(long long x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) write(x / 10); putchar(x % 10 + '0'); } void writeln(long long x) { write(x); puts(""); } int n, m, k; struct node { int x, y; }; vector<node> v[90005]; int ans = 1e9, dp[305][305]; inline int dis(node x, node y) { return abs(x.x - y.x) + abs(x.y - y.y); } inline bool cmp(node x, node y) { return dp[x.x][x.y] < dp[y.x][y.y]; } signed main() { n = read(); m = read(); k = read(); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) v[read()].push_back((node){i, j}); memset(dp, 0x3f, sizeof(dp)); for (int i = 0; i < v[1].size(); i++) { int x = v[1][i].x, y = v[1][i].y; dp[x][y] = x + y - 2; } for (int i = (int)(1); i <= (int)(k - 1); i++) { sort(v[i].begin(), v[i].end(), cmp); int p = min((int)v[i].size(), 600); for (int j = 0; j < p; j++) { int x = v[i][j].x, y = v[i][j].y; for (int l = 0; l < v[i + 1].size(); l++) { int xx = v[i + 1][l].x, yy = v[i + 1][l].y; dp[xx][yy] = min(dp[xx][yy], dp[x][y] + dis(v[i][j], v[i + 1][l])); } } } for (int i = 0; i < v[k].size(); i++) ans = min(ans, dp[v[k][i].x][v[k][i].y]); writeln(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; inline long long read() { long long x = 0; char ch = getchar(); bool f = 0; for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = 1; for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0'; return f ? -x : x; } void write(long long x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) write(x / 10); putchar(x % 10 + '0'); } void writeln(long long x) { write(x); puts(""); } int n, m, k; struct node { int x, y; }; vector<node> v[90005]; int ans = 1e9, dp[305][305]; inline int dis(node x, node y) { return abs(x.x - y.x) + abs(x.y - y.y); } inline bool cmp(node x, node y) { return dp[x.x][x.y] < dp[y.x][y.y]; } signed main() { n = read(); m = read(); k = read(); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) v[read()].push_back((node){i, j}); memset(dp, 0x3f, sizeof(dp)); for (int i = 0; i < v[1].size(); i++) { int x = v[1][i].x, y = v[1][i].y; dp[x][y] = x + y - 2; } for (int i = (int)(1); i <= (int)(k - 1); i++) { sort(v[i].begin(), v[i].end(), cmp); int p = min((int)v[i].size(), 600); for (int j = 0; j < p; j++) { int x = v[i][j].x, y = v[i][j].y; for (int l = 0; l < v[i + 1].size(); l++) { int xx = v[i + 1][l].x, yy = v[i + 1][l].y; dp[xx][yy] = min(dp[xx][yy], dp[x][y] + dis(v[i][j], v[i + 1][l])); } } } for (int i = 0; i < v[k].size(); i++) ans = min(ans, dp[v[k][i].x][v[k][i].y]); writeln(ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const int INF = 1e9 + 7; const double PI = acos(-1); const int maxn = 310; int n, m, k; int dp[maxn][maxn]; vector<pair<int, int> > a[maxn * maxn]; vector<int> b[2][maxn]; void init() {} void solve() {} int main() { cin >> n >> m >> k; int num; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> num; a[num].push_back(make_pair(i, j)); } } int cur = 1, lat = 0; for (int i = 0; i < a[1].size(); i++) { int X = a[1][i].first; int Y = a[1][i].second; dp[X][Y] = X + Y; b[0][Y].push_back(X); } for (int i = 2; i <= k; i++) { for (int j = 0; j < m; j++) { b[cur][j].clear(); } for (int j = 0; j < a[i].size(); j++) { int X = a[i][j].first; int Y = a[i][j].second; int mi = INF; for (int l = 0; l < m; l++) { int t = lower_bound((b[lat][l]).begin(), (b[lat][l]).end(), X) - b[lat][l].begin(); if (t != b[lat][l].size()) { int xx = b[lat][l][t]; int yy = l; mi = min(mi, dp[b[lat][l][t]][l] + abs(b[lat][l][t] - X) + abs(l - Y)); } if (t != 0) { t--; mi = min(mi, dp[b[lat][l][t]][l] + abs(b[lat][l][t] - X) + abs(l - Y)); } } dp[X][Y] = mi; b[cur][Y].push_back(X); } swap(cur, lat); } cout << dp[a[k][0].first][a[k][0].second] << 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; const long long mod = 1e9 + 7; const int INF = 1e9 + 7; const double PI = acos(-1); const int maxn = 310; int n, m, k; int dp[maxn][maxn]; vector<pair<int, int> > a[maxn * maxn]; vector<int> b[2][maxn]; void init() {} void solve() {} int main() { cin >> n >> m >> k; int num; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> num; a[num].push_back(make_pair(i, j)); } } int cur = 1, lat = 0; for (int i = 0; i < a[1].size(); i++) { int X = a[1][i].first; int Y = a[1][i].second; dp[X][Y] = X + Y; b[0][Y].push_back(X); } for (int i = 2; i <= k; i++) { for (int j = 0; j < m; j++) { b[cur][j].clear(); } for (int j = 0; j < a[i].size(); j++) { int X = a[i][j].first; int Y = a[i][j].second; int mi = INF; for (int l = 0; l < m; l++) { int t = lower_bound((b[lat][l]).begin(), (b[lat][l]).end(), X) - b[lat][l].begin(); if (t != b[lat][l].size()) { int xx = b[lat][l][t]; int yy = l; mi = min(mi, dp[b[lat][l][t]][l] + abs(b[lat][l][t] - X) + abs(l - Y)); } if (t != 0) { t--; mi = min(mi, dp[b[lat][l][t]][l] + abs(b[lat][l][t] - X) + abs(l - Y)); } } dp[X][Y] = mi; b[cur][Y].push_back(X); } swap(cur, lat); } cout << dp[a[k][0].first][a[k][0].second] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 301; int n, m, p, a[N][N]; vector<pair<int, int> > pos[N * N]; int cost[N][N]; int dr[] = {0, -1, 0, 1}; int dc[] = {-1, 0, 1, 0}; int vis[N][N]; class state { public: int x, y, cost; state(int a, int b, int c) { x = a; y = b; cost = c; } bool operator<(const state& s) const { return cost < s.cost; } }; void BFS(int tar) { queue<state> q; vector<state> v; memset(vis, -1, sizeof(vis)); for (int i = 0; i < pos[tar - 1].size(); ++i) { int x = pos[tar - 1][i].first; int y = pos[tar - 1][i].second; v.push_back(state(x, y, cost[x][y])); } sort(v.begin(), v.end()); int last = v[0].cost, idx; for (int i = 0; v[i].cost == last; ++i) { q.push(v[i]); vis[v[i].x][v[i].y] = v[i].cost; idx = i; } ++idx; while (q.size()) { state src = q.front(); q.pop(); int x = src.x, y = src.y; while (idx < v.size() && v[idx].cost == last) { int a = v[idx].x, b = v[idx].y; if (vis[a][b] != -1) { ++idx; continue; } vis[a][b] = v[idx].cost; q.push(v[idx++]); } for (int i = 0; i < 4; ++i) { int nx = dr[i] + x; int ny = dc[i] + y; if (nx < 0 || ny < 0 || nx == n || ny == m) continue; if (vis[nx][ny] == -1) { vis[nx][ny] = vis[x][y] + 1; q.push(state(nx, ny, vis[nx][ny])); last = vis[nx][ny]; if (a[nx][ny] == tar) cost[nx][ny] = vis[nx][ny]; } } } } int main() { cin >> n >> m >> p; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { scanf("%d", &a[i][j]); pos[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) cost[i][j] = i + j; else cost[i][j] = 1 << 25; } } for (int k = 2; k <= p; ++k) { if (pos[k].size() * pos[k - 1].size() >= n * m) BFS(k); else { for (int i = 0; i < pos[k - 1].size(); ++i) { int x = pos[k - 1][i].first; int y = pos[k - 1][i].second; for (int j = 0; j < pos[k].size(); ++j) { int a = pos[k][j].first; int b = pos[k][j].second; cost[a][b] = min(cost[a][b], cost[x][y] + abs(a - x) + abs(b - y)); } } } } cout << cost[pos[p][0].first][pos[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 N = 301; int n, m, p, a[N][N]; vector<pair<int, int> > pos[N * N]; int cost[N][N]; int dr[] = {0, -1, 0, 1}; int dc[] = {-1, 0, 1, 0}; int vis[N][N]; class state { public: int x, y, cost; state(int a, int b, int c) { x = a; y = b; cost = c; } bool operator<(const state& s) const { return cost < s.cost; } }; void BFS(int tar) { queue<state> q; vector<state> v; memset(vis, -1, sizeof(vis)); for (int i = 0; i < pos[tar - 1].size(); ++i) { int x = pos[tar - 1][i].first; int y = pos[tar - 1][i].second; v.push_back(state(x, y, cost[x][y])); } sort(v.begin(), v.end()); int last = v[0].cost, idx; for (int i = 0; v[i].cost == last; ++i) { q.push(v[i]); vis[v[i].x][v[i].y] = v[i].cost; idx = i; } ++idx; while (q.size()) { state src = q.front(); q.pop(); int x = src.x, y = src.y; while (idx < v.size() && v[idx].cost == last) { int a = v[idx].x, b = v[idx].y; if (vis[a][b] != -1) { ++idx; continue; } vis[a][b] = v[idx].cost; q.push(v[idx++]); } for (int i = 0; i < 4; ++i) { int nx = dr[i] + x; int ny = dc[i] + y; if (nx < 0 || ny < 0 || nx == n || ny == m) continue; if (vis[nx][ny] == -1) { vis[nx][ny] = vis[x][y] + 1; q.push(state(nx, ny, vis[nx][ny])); last = vis[nx][ny]; if (a[nx][ny] == tar) cost[nx][ny] = vis[nx][ny]; } } } } int main() { cin >> n >> m >> p; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { scanf("%d", &a[i][j]); pos[a[i][j]].push_back(make_pair(i, j)); if (a[i][j] == 1) cost[i][j] = i + j; else cost[i][j] = 1 << 25; } } for (int k = 2; k <= p; ++k) { if (pos[k].size() * pos[k - 1].size() >= n * m) BFS(k); else { for (int i = 0; i < pos[k - 1].size(); ++i) { int x = pos[k - 1][i].first; int y = pos[k - 1][i].second; for (int j = 0; j < pos[k].size(); ++j) { int a = pos[k][j].first; int b = pos[k][j].second; cost[a][b] = min(cost[a][b], cost[x][y] + abs(a - x) + abs(b - y)); } } } } cout << cost[pos[p][0].first][pos[p][0].second] << endl; return 0; } ```
#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 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 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 type[305][305], check[305]; long long int dp[305][305], tmp[305][305]; struct P { int x, y; }; vector<P> arr[305 * 305]; int main() { 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", &type[i][j]); arr[type[i][j]].push_back((P){i, j}); dp[i][j] = tmp[i][j] = 10000000000000000LL; } } arr[0].push_back((P){0, 0}); check[0] = 1; for (int i = 0; i < m; i++) { tmp[0][i] = i; } for (int i = 1; i <= p; i++) { for (int j = 0; j < arr[i].size(); j++) { P in = arr[i][j]; for (int k = in.x; k >= 0; k--) { if (check[k] == 0) continue; dp[in.x][in.y] = min(dp[in.x][in.y], in.x - k + tmp[k][in.y]); } for (int k = in.x; k < n; k++) { if (check[k] == 0) continue; dp[in.x][in.y] = min(dp[in.x][in.y], k - in.x + tmp[k][in.y]); } } for (int j = 0; j < arr[i - 1].size(); j++) { P in = arr[i - 1][j]; if (check[in.x]) { check[in.x] = 0; for (int k = 0; k < m; k++) { tmp[in.x][k] = 10000000000000000LL; } } } for (int j = 0; j < arr[i].size(); j++) { P in = arr[i][j]; long long int mi = 10000000000000000LL; if (check[in.x]) continue; check[in.x] = 1; for (int k = 0; k < m; k++) { if (type[in.x][k] == i) mi = dp[in.x][k]; else mi++; tmp[in.x][k] = min(tmp[in.x][k], mi); } mi = 10000000000000000LL; for (int k = m - 1; k >= 0; k--) { if (type[in.x][k] == i) mi = dp[in.x][k]; else mi++; tmp[in.x][k] = min(tmp[in.x][k], mi); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (type[i][j] == p) { printf("%lld\n", dp[i][j]); 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 type[305][305], check[305]; long long int dp[305][305], tmp[305][305]; struct P { int x, y; }; vector<P> arr[305 * 305]; int main() { 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", &type[i][j]); arr[type[i][j]].push_back((P){i, j}); dp[i][j] = tmp[i][j] = 10000000000000000LL; } } arr[0].push_back((P){0, 0}); check[0] = 1; for (int i = 0; i < m; i++) { tmp[0][i] = i; } for (int i = 1; i <= p; i++) { for (int j = 0; j < arr[i].size(); j++) { P in = arr[i][j]; for (int k = in.x; k >= 0; k--) { if (check[k] == 0) continue; dp[in.x][in.y] = min(dp[in.x][in.y], in.x - k + tmp[k][in.y]); } for (int k = in.x; k < n; k++) { if (check[k] == 0) continue; dp[in.x][in.y] = min(dp[in.x][in.y], k - in.x + tmp[k][in.y]); } } for (int j = 0; j < arr[i - 1].size(); j++) { P in = arr[i - 1][j]; if (check[in.x]) { check[in.x] = 0; for (int k = 0; k < m; k++) { tmp[in.x][k] = 10000000000000000LL; } } } for (int j = 0; j < arr[i].size(); j++) { P in = arr[i][j]; long long int mi = 10000000000000000LL; if (check[in.x]) continue; check[in.x] = 1; for (int k = 0; k < m; k++) { if (type[in.x][k] == i) mi = dp[in.x][k]; else mi++; tmp[in.x][k] = min(tmp[in.x][k], mi); } mi = 10000000000000000LL; for (int k = m - 1; k >= 0; k--) { if (type[in.x][k] == i) mi = dp[in.x][k]; else mi++; tmp[in.x][k] = min(tmp[in.x][k], mi); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (type[i][j] == p) { printf("%lld\n", dp[i][j]); return 0; } } } } ```
#include <bits/stdc++.h> using namespace std; const int dx[4] = {0, 1, 0, -1}; const int dy[4] = {1, 0, -1, 0}; int N, M, P; inline int getid(pair<int, int> point) { return (point.first - 1) * M + point.second; } inline int getDist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } bool vis[310 * 310]; int dist[310][310], dp[310][310], grid[310][310]; vector<pair<int, int> > typePos[310 * 310]; queue<pair<int, int> > q; 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]); typePos[grid[i][j]].push_back(pair<int, int>(i, j)); } memset(dp, 0x3f, sizeof dp); for (int i = 0; i < (int)typePos[1].size(); i++) dp[typePos[1][i].first][typePos[1][i].second] = getDist(pair<int, int>(1, 1), typePos[1][i]); for (int type = 1; type < P; type++) { vector<pair<int, int> > &cur = typePos[type], &nxt = typePos[type + 1]; if (cur.size() * nxt.size() <= N * M) { for (int i = 0; i < (int)cur.size(); i++) { for (int j = 0; j < (int)nxt.size(); j++) { dp[nxt[j].first][nxt[j].second] = min(dp[nxt[j].first][nxt[j].second], dp[cur[i].first][cur[i].second] + getDist(cur[i], nxt[j])); } } } else { memset(vis, 0, sizeof vis); memset(dist, 0x3f, sizeof dist); while (!q.empty()) q.pop(); for (int i = 0; i < (int)cur.size(); i++) { dist[cur[i].first][cur[i].second] = dp[cur[i].first][cur[i].second]; q.push(cur[i]); vis[getid(cur[i])] = true; } while (!q.empty()) { int x = q.front().first, y = q.front().second; q.pop(); vis[getid(pair<int, int>(x, y))] = false; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (1 <= nx && nx <= N && 1 <= ny && ny <= M && dist[nx][ny] > dist[x][y] + 1) { dist[nx][ny] = dist[x][y] + 1; if (!vis[getid(pair<int, int>(nx, ny))]) { vis[getid(pair<int, int>(nx, ny))] = true; q.push(pair<int, int>(nx, ny)); } } } } for (int i = 0; i < (int)nxt.size(); i++) dp[nxt[i].first][nxt[i].second] = dist[nxt[i].first][nxt[i].second]; } } printf("%d\n", dp[typePos[P][0].first][typePos[P][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; const int dx[4] = {0, 1, 0, -1}; const int dy[4] = {1, 0, -1, 0}; int N, M, P; inline int getid(pair<int, int> point) { return (point.first - 1) * M + point.second; } inline int getDist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } bool vis[310 * 310]; int dist[310][310], dp[310][310], grid[310][310]; vector<pair<int, int> > typePos[310 * 310]; queue<pair<int, int> > q; 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]); typePos[grid[i][j]].push_back(pair<int, int>(i, j)); } memset(dp, 0x3f, sizeof dp); for (int i = 0; i < (int)typePos[1].size(); i++) dp[typePos[1][i].first][typePos[1][i].second] = getDist(pair<int, int>(1, 1), typePos[1][i]); for (int type = 1; type < P; type++) { vector<pair<int, int> > &cur = typePos[type], &nxt = typePos[type + 1]; if (cur.size() * nxt.size() <= N * M) { for (int i = 0; i < (int)cur.size(); i++) { for (int j = 0; j < (int)nxt.size(); j++) { dp[nxt[j].first][nxt[j].second] = min(dp[nxt[j].first][nxt[j].second], dp[cur[i].first][cur[i].second] + getDist(cur[i], nxt[j])); } } } else { memset(vis, 0, sizeof vis); memset(dist, 0x3f, sizeof dist); while (!q.empty()) q.pop(); for (int i = 0; i < (int)cur.size(); i++) { dist[cur[i].first][cur[i].second] = dp[cur[i].first][cur[i].second]; q.push(cur[i]); vis[getid(cur[i])] = true; } while (!q.empty()) { int x = q.front().first, y = q.front().second; q.pop(); vis[getid(pair<int, int>(x, y))] = false; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (1 <= nx && nx <= N && 1 <= ny && ny <= M && dist[nx][ny] > dist[x][y] + 1) { dist[nx][ny] = dist[x][y] + 1; if (!vis[getid(pair<int, int>(nx, ny))]) { vis[getid(pair<int, int>(nx, ny))] = true; q.push(pair<int, int>(nx, ny)); } } } } for (int i = 0; i < (int)nxt.size(); i++) dp[nxt[i].first][nxt[i].second] = dist[nxt[i].first][nxt[i].second]; } } printf("%d\n", dp[typePos[P][0].first][typePos[P][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; template <class T> T abs(T x) { return x > 0 ? x : -x; } template <class T> T gcd(T a, T b) { return a ? gcd(b % a, a) : b; } template <class T> T sqr(T a) { return a * a; } template <class T> T sgn(T a) { return a > 0 ? 1 : (a < 0 ? -1 : 0); } int n; int m; const int N = 310; vector<pair<int, pair<int, int>>> t[N * N]; pair<int, pair<int, int>> d[N][N]; bool was[N][N]; int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int main() { int p; scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; scanf("%d", &x); if (x == 1) t[x].push_back(make_pair(i + j, make_pair(i, j))); else t[x].push_back(make_pair(2e9, make_pair(i, j))); } for (int k = 1; k < p; k++) { if ((long long)((int)(t[k]).size()) * ((int)(t[k + 1]).size()) >= n * m) { int l = 0; vector<pair<int, int>> q; memset(d, 127, sizeof(d)); memset(was, false, sizeof(was)); sort((t[k]).begin(), (t[k]).end()); int j = 0; q.push_back(t[k][j].second), d[t[k][j].second.first][t[k][j].second.second] = t[k][j]; j++; while (l < ((int)(q).size())) { pair<int, int> cur = q[l++]; while (j < ((int)(t[k]).size()) && d[cur.first][cur.second].first + 1 >= t[k][j].first) { q.push_back(t[k][j].second); d[t[k][j].second.first][t[k][j].second.second] = t[k][j]; j++; } if (was[cur.first][cur.second]) continue; was[cur.first][cur.second] = true; for (int i = 0; i < 4; i++) { int x = cur.first + dx[i]; int y = cur.second + dy[i]; if (x < 0 || y < 0 || x >= n || y >= m) continue; if (d[x][y].first > d[cur.first][cur.second].first + 1) { d[x][y] = make_pair(d[cur.first][cur.second].first + 1, cur); q.push_back(make_pair(x, y)); } } } for (auto& w : t[k + 1]) w.first = d[w.second.first][w.second.second].first; } else { for (auto w1 : t[k]) for (auto& w2 : t[k + 1]) { w2.first = min(w1.first + abs(w1.second.first - w2.second.first) + abs(w1.second.second - w2.second.second), w2.first); } } } int ans = 2e9; for (auto w : t[p]) ans = min(w.first, ans); cout << ans << 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; template <class T> T abs(T x) { return x > 0 ? x : -x; } template <class T> T gcd(T a, T b) { return a ? gcd(b % a, a) : b; } template <class T> T sqr(T a) { return a * a; } template <class T> T sgn(T a) { return a > 0 ? 1 : (a < 0 ? -1 : 0); } int n; int m; const int N = 310; vector<pair<int, pair<int, int>>> t[N * N]; pair<int, pair<int, int>> d[N][N]; bool was[N][N]; int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int main() { int p; scanf("%d%d%d", &n, &m, &p); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x; scanf("%d", &x); if (x == 1) t[x].push_back(make_pair(i + j, make_pair(i, j))); else t[x].push_back(make_pair(2e9, make_pair(i, j))); } for (int k = 1; k < p; k++) { if ((long long)((int)(t[k]).size()) * ((int)(t[k + 1]).size()) >= n * m) { int l = 0; vector<pair<int, int>> q; memset(d, 127, sizeof(d)); memset(was, false, sizeof(was)); sort((t[k]).begin(), (t[k]).end()); int j = 0; q.push_back(t[k][j].second), d[t[k][j].second.first][t[k][j].second.second] = t[k][j]; j++; while (l < ((int)(q).size())) { pair<int, int> cur = q[l++]; while (j < ((int)(t[k]).size()) && d[cur.first][cur.second].first + 1 >= t[k][j].first) { q.push_back(t[k][j].second); d[t[k][j].second.first][t[k][j].second.second] = t[k][j]; j++; } if (was[cur.first][cur.second]) continue; was[cur.first][cur.second] = true; for (int i = 0; i < 4; i++) { int x = cur.first + dx[i]; int y = cur.second + dy[i]; if (x < 0 || y < 0 || x >= n || y >= m) continue; if (d[x][y].first > d[cur.first][cur.second].first + 1) { d[x][y] = make_pair(d[cur.first][cur.second].first + 1, cur); q.push_back(make_pair(x, y)); } } } for (auto& w : t[k + 1]) w.first = d[w.second.first][w.second.second].first; } else { for (auto w1 : t[k]) for (auto& w2 : t[k + 1]) { w2.first = min(w1.first + abs(w1.second.first - w2.second.first) + abs(w1.second.second - w2.second.second), w2.first); } } } int ans = 2e9; for (auto w : t[p]) ans = min(w.first, ans); cout << ans << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 300; struct Cood { int x; int y; }; vector<Cood> G[maxn * maxn + 5]; queue<Cood> Q; int dx[] = {0, 0, -1, 1}; int dy[] = {1, -1, 0, 0}; int dp[maxn + 5][maxn + 5]; int temp[maxn + 5][maxn + 5]; bool book[maxn + 5][maxn + 5]; int main(void) { int n, m, p; scanf("%d%d%d", &n, &m, &p); memset((dp), (127), sizeof(dp)); int a; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &a); G[a].push_back((Cood){i, j}); if (a == 1) dp[i][j] = i + j - 2; } } int k = sqrt(n * m); for (int i = 2; i <= p; ++i) { if (G[i].size() < k) { for (auto g1 : G[i]) { for (auto g2 : G[i - 1]) { dp[g1.x][g1.y] = min(dp[g1.x][g1.y], dp[g2.x][g2.y] + abs(g1.x - g2.x) + abs(g1.y - g2.y)); } } } else { memset((temp), (127), sizeof(temp)); memset((book), (0), sizeof(book)); for (auto g : G[i - 1]) { Q.push(g); temp[g.x][g.y] = dp[g.x][g.y]; } while (!Q.empty()) { Cood now = Q.front(); Q.pop(); book[now.x][now.y] = false; for (int i = 0; i <= 3; ++i) { Cood tmp; tmp.x = now.x + dx[i]; tmp.y = now.y + dy[i]; if (tmp.x < 1 || tmp.x > n || tmp.y < 1 || tmp.y > m) continue; if (temp[tmp.x][tmp.y] > temp[now.x][now.y] + 1) { temp[tmp.x][tmp.y] = temp[now.x][now.y] + 1; if (!book[tmp.x][tmp.y]) { book[tmp.x][tmp.y] = true; Q.push(tmp); } } } } for (auto g : G[i]) dp[g.x][g.y] = temp[g.x][g.y]; } } Cood &ans = G[p][0]; printf("%d\n", dp[ans.x][ans.y]); }
### 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; struct Cood { int x; int y; }; vector<Cood> G[maxn * maxn + 5]; queue<Cood> Q; int dx[] = {0, 0, -1, 1}; int dy[] = {1, -1, 0, 0}; int dp[maxn + 5][maxn + 5]; int temp[maxn + 5][maxn + 5]; bool book[maxn + 5][maxn + 5]; int main(void) { int n, m, p; scanf("%d%d%d", &n, &m, &p); memset((dp), (127), sizeof(dp)); int a; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &a); G[a].push_back((Cood){i, j}); if (a == 1) dp[i][j] = i + j - 2; } } int k = sqrt(n * m); for (int i = 2; i <= p; ++i) { if (G[i].size() < k) { for (auto g1 : G[i]) { for (auto g2 : G[i - 1]) { dp[g1.x][g1.y] = min(dp[g1.x][g1.y], dp[g2.x][g2.y] + abs(g1.x - g2.x) + abs(g1.y - g2.y)); } } } else { memset((temp), (127), sizeof(temp)); memset((book), (0), sizeof(book)); for (auto g : G[i - 1]) { Q.push(g); temp[g.x][g.y] = dp[g.x][g.y]; } while (!Q.empty()) { Cood now = Q.front(); Q.pop(); book[now.x][now.y] = false; for (int i = 0; i <= 3; ++i) { Cood tmp; tmp.x = now.x + dx[i]; tmp.y = now.y + dy[i]; if (tmp.x < 1 || tmp.x > n || tmp.y < 1 || tmp.y > m) continue; if (temp[tmp.x][tmp.y] > temp[now.x][now.y] + 1) { temp[tmp.x][tmp.y] = temp[now.x][now.y] + 1; if (!book[tmp.x][tmp.y]) { book[tmp.x][tmp.y] = true; Q.push(tmp); } } } } for (auto g : G[i]) dp[g.x][g.y] = temp[g.x][g.y]; } } Cood &ans = G[p][0]; printf("%d\n", dp[ans.x][ans.y]); } ```
#include <bits/stdc++.h> using namespace std; struct Coord { int x, y; Coord() {} Coord(int _x, int _y) { x = _x; y = _y; } int distance(const Coord& other) { return abs(other.x - x) + abs(other.y - y); } }; struct Node { Node(){}; Node(int _x, int _y, int _l) { x = _x; y = _y; level = _l; } int x, y, level; }; inline bool inside(int x, int y, int n, int m) { return 0 <= x && x < n && 0 <= y && y < m; } int dx[] = {0, 0, 1, -1}; int dy[] = {-1, 1, 0, 0}; int main() { int N, M, P; cin >> N >> M >> P; vector<vector<int>> table(N, vector<int>(M, 0)); vector<vector<Coord>> allCells(P + 1, vector<Coord>()); for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { cin >> table[i][j]; allCells[table[i][j]].push_back(Coord(i, j)); } } allCells[0].push_back(Coord(0, 0)); vector<vector<int>> dp(N, vector<int>(M, 1 << 29)); for (auto& cell : allCells[1]) { dp[cell.x][cell.y] = cell.distance(Coord(0, 0)); } for (int i = 2; i <= P; ++i) { if (allCells[i].size() * allCells[i - 1].size() <= N * M) { for (auto& cell1 : allCells[i - 1]) { for (auto& cell2 : allCells[i]) { dp[cell2.x][cell2.y] = min(dp[cell2.x][cell2.y], dp[cell1.x][cell1.y] + cell1.distance(cell2)); } } } else { cerr << "bfs?"; queue<Coord> Q; vector<vector<int>> vis(N, vector<int>(M, -1)); for (auto& cell : allCells[i - 1]) { Q.push(cell); vis[cell.x][cell.y] = dp[cell.x][cell.y]; } while (!Q.empty()) { Coord cur = Q.front(); Q.pop(); for (int k = 0; k < 4; ++k) { int xn = cur.x + dx[k]; int yn = cur.y + dy[k]; if (!inside(xn, yn, N, M)) { continue; } if (vis[xn][yn] == -1 || (vis[xn][yn] > vis[cur.x][cur.y] + 1)) { vis[xn][yn] = vis[cur.x][cur.y] + 1; Q.push(Coord(xn, yn)); } } } for (auto& cell : allCells[i]) { dp[cell.x][cell.y] = vis[cell.x][cell.y]; } } } Coord fl = allCells[P][0]; cout << dp[fl.x][fl.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> using namespace std; struct Coord { int x, y; Coord() {} Coord(int _x, int _y) { x = _x; y = _y; } int distance(const Coord& other) { return abs(other.x - x) + abs(other.y - y); } }; struct Node { Node(){}; Node(int _x, int _y, int _l) { x = _x; y = _y; level = _l; } int x, y, level; }; inline bool inside(int x, int y, int n, int m) { return 0 <= x && x < n && 0 <= y && y < m; } int dx[] = {0, 0, 1, -1}; int dy[] = {-1, 1, 0, 0}; int main() { int N, M, P; cin >> N >> M >> P; vector<vector<int>> table(N, vector<int>(M, 0)); vector<vector<Coord>> allCells(P + 1, vector<Coord>()); for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { cin >> table[i][j]; allCells[table[i][j]].push_back(Coord(i, j)); } } allCells[0].push_back(Coord(0, 0)); vector<vector<int>> dp(N, vector<int>(M, 1 << 29)); for (auto& cell : allCells[1]) { dp[cell.x][cell.y] = cell.distance(Coord(0, 0)); } for (int i = 2; i <= P; ++i) { if (allCells[i].size() * allCells[i - 1].size() <= N * M) { for (auto& cell1 : allCells[i - 1]) { for (auto& cell2 : allCells[i]) { dp[cell2.x][cell2.y] = min(dp[cell2.x][cell2.y], dp[cell1.x][cell1.y] + cell1.distance(cell2)); } } } else { cerr << "bfs?"; queue<Coord> Q; vector<vector<int>> vis(N, vector<int>(M, -1)); for (auto& cell : allCells[i - 1]) { Q.push(cell); vis[cell.x][cell.y] = dp[cell.x][cell.y]; } while (!Q.empty()) { Coord cur = Q.front(); Q.pop(); for (int k = 0; k < 4; ++k) { int xn = cur.x + dx[k]; int yn = cur.y + dy[k]; if (!inside(xn, yn, N, M)) { continue; } if (vis[xn][yn] == -1 || (vis[xn][yn] > vis[cur.x][cur.y] + 1)) { vis[xn][yn] = vis[cur.x][cur.y] + 1; Q.push(Coord(xn, yn)); } } } for (auto& cell : allCells[i]) { dp[cell.x][cell.y] = vis[cell.x][cell.y]; } } } Coord fl = allCells[P][0]; cout << dp[fl.x][fl.y]; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 333; vector<pair<int, pair<int, int> > > v[maxn * maxn]; int dist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } int n, m, p, w; int main() { scanf("%d%d%d", &m, &n, &p); for (int i = 1; i <= m; ++i) for (int j = 1; j <= n; ++j) { scanf("%d", &w); v[w].push_back(pair<int, pair<int, int> >(INT_MAX, pair<int, int>(i, j))); } for (int i = 0; i < v[1].size(); ++i) v[1][i].first = dist(pair<int, int>(1, 1), v[1][i].second); for (int i = 2; i <= p; ++i) { sort(v[i - 1].begin(), v[i - 1].end()); for (int j = 0; j < v[i].size(); ++j) { for (int k = 0; k < min((int)v[i - 1].size(), m + n); ++k) v[i][j].first = min(v[i][j].first, v[i - 1][k].first + dist(v[i][j].second, v[i - 1][k].second)); } } int res = INT_MAX; for (int i = 0; i < v[p].size(); ++i) res = min(res, v[p][i].first); printf("%d\n", res); }
### 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 = 333; vector<pair<int, pair<int, int> > > v[maxn * maxn]; int dist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } int n, m, p, w; int main() { scanf("%d%d%d", &m, &n, &p); for (int i = 1; i <= m; ++i) for (int j = 1; j <= n; ++j) { scanf("%d", &w); v[w].push_back(pair<int, pair<int, int> >(INT_MAX, pair<int, int>(i, j))); } for (int i = 0; i < v[1].size(); ++i) v[1][i].first = dist(pair<int, int>(1, 1), v[1][i].second); for (int i = 2; i <= p; ++i) { sort(v[i - 1].begin(), v[i - 1].end()); for (int j = 0; j < v[i].size(); ++j) { for (int k = 0; k < min((int)v[i - 1].size(), m + n); ++k) v[i][j].first = min(v[i][j].first, v[i - 1][k].first + dist(v[i][j].second, v[i - 1][k].second)); } } int res = INT_MAX; for (int i = 0; i < v[p].size(); ++i) res = min(res, v[p][i].first); printf("%d\n", res); } ```
#include <bits/stdc++.h> const long long INF = (long long)1e18 + 123; const int inf = (int)2e9 + 123; const int mod = 1e9 + 7; using namespace std; int n, m, p, a[311][311]; int dp[311][311]; vector<pair<int, int> > c[300 * 300 + 123]; vector<int> col[311]; bool is[311]; int main() { unsigned int FOR; asm("rdtsc" : "=A"(FOR)); srand(FOR); 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 >> a[i][j]; dp[i][j] = inf; if (a[i][j] == 1) { dp[i][j] = (i - 1) + (j - 1); } c[a[i][j]].push_back(make_pair(i, j)); } } for (int k = 1; k < p; k++) { memset(is, 0, sizeof(is)); for (int i = 1; i <= m; i++) { col[i].clear(); } for (auto to : c[k + 1]) { col[to.second].push_back(to.first); } for (auto to : c[k]) { is[to.first] = 1; } for (int i = 1; i <= n; i++) { if (!is[i]) continue; int mn = inf; for (int j = 1; j <= m; j++) { mn++; if (a[i][j] == k) { mn = min(mn, dp[i][j]); } for (auto to : col[j]) { dp[to][j] = min(dp[to][j], mn + abs(to - i)); } } mn = inf; for (int j = m; j >= 1; j--) { mn++; if (a[i][j] == k) { mn = min(mn, dp[i][j]); } for (auto to : col[j]) { dp[to][j] = min(dp[to][j], mn + abs(to - i)); } } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == p) { cout << dp[i][j] << " "; return 0; } } } 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> const long long INF = (long long)1e18 + 123; const int inf = (int)2e9 + 123; const int mod = 1e9 + 7; using namespace std; int n, m, p, a[311][311]; int dp[311][311]; vector<pair<int, int> > c[300 * 300 + 123]; vector<int> col[311]; bool is[311]; int main() { unsigned int FOR; asm("rdtsc" : "=A"(FOR)); srand(FOR); 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 >> a[i][j]; dp[i][j] = inf; if (a[i][j] == 1) { dp[i][j] = (i - 1) + (j - 1); } c[a[i][j]].push_back(make_pair(i, j)); } } for (int k = 1; k < p; k++) { memset(is, 0, sizeof(is)); for (int i = 1; i <= m; i++) { col[i].clear(); } for (auto to : c[k + 1]) { col[to.second].push_back(to.first); } for (auto to : c[k]) { is[to.first] = 1; } for (int i = 1; i <= n; i++) { if (!is[i]) continue; int mn = inf; for (int j = 1; j <= m; j++) { mn++; if (a[i][j] == k) { mn = min(mn, dp[i][j]); } for (auto to : col[j]) { dp[to][j] = min(dp[to][j], mn + abs(to - i)); } } mn = inf; for (int j = m; j >= 1; j--) { mn++; if (a[i][j] == k) { mn = min(mn, dp[i][j]); } for (auto to : col[j]) { dp[to][j] = min(dp[to][j], mn + abs(to - i)); } } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == p) { cout << dp[i][j] << " "; return 0; } } } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int vc = 1e9 + 7; const int maxN = 310; const int maxM = maxN * maxN; int r[maxN][maxN], le[maxN][maxN], ri[maxN][maxN], a[maxN][maxN]; int n, m, p; int head[maxM], link[maxM], X[maxM], Y[maxM], W[maxM], Co[maxM]; void solve1(int i) { for (int j = 1; j <= n; j++) { le[j][0] = -1; ri[j][m + 1] = -1; for (int k = 1; k <= m; k++) if (a[j][k] == i - 1) le[j][k] = k; else le[j][k] = le[j][k - 1]; for (int k = m; k > 0; k--) if (a[j][k] == i - 1) ri[j][k] = k; else ri[j][k] = ri[j][k + 1]; } int t; t = head[i]; while (t > 0) { int x, y; x = X[t]; y = Y[t]; for (int j = 1; j <= n; j++) { if (le[j][y] > -1 && (r[j][le[j][y]] + abs(j - x) + abs(le[j][y] - y) < r[x][y])) r[x][y] = r[j][le[j][y]] + abs(j - x) + abs(le[j][y] - y); if (ri[j][y] > -1 && (r[j][ri[j][y]] + abs(j - x) + abs(ri[j][y] - y) < r[x][y])) r[x][y] = r[j][ri[j][y]] + abs(j - x) + abs(ri[j][y] - y); } if (i == p) cout << r[x][y]; t = link[t]; } } void solve2(int i) { int t, t2, x, x2, y, y2; t = head[i]; while (t > 0) { x = X[t]; y = Y[t]; t2 = head[i - 1]; while (t2 > 0) { x2 = X[t2]; y2 = Y[t2]; if (r[x2][y2] + abs(x - x2) + abs(y - y2) < r[x][y]) r[x][y] = r[x2][y2] + abs(x - x2) + abs(y - y2); t2 = link[t2]; } if (i == p) cout << r[x][y]; t = link[t]; } } int main() { scanf("%d%d%d", &n, &m, &p); if (p == 1) { cout << 0; return 0; } for (int i = 1; i <= p; i++) head[i] = 0; for (int i = 1; i <= p; i++) Co[i] = 0; long long P = 0, MaxC = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); Co[a[i][j]]++; P++; X[P] = i; Y[P] = j; W[P] = a[i][j]; link[P] = head[W[P]]; head[W[P]] = P; } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == 1) r[i][j] = i + j - 2; else r[i][j] = vc; for (int i = 2; i <= p; i++) if (Co[i] * Co[i - 1] >= n * m) solve1(i); else solve2(i); 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 vc = 1e9 + 7; const int maxN = 310; const int maxM = maxN * maxN; int r[maxN][maxN], le[maxN][maxN], ri[maxN][maxN], a[maxN][maxN]; int n, m, p; int head[maxM], link[maxM], X[maxM], Y[maxM], W[maxM], Co[maxM]; void solve1(int i) { for (int j = 1; j <= n; j++) { le[j][0] = -1; ri[j][m + 1] = -1; for (int k = 1; k <= m; k++) if (a[j][k] == i - 1) le[j][k] = k; else le[j][k] = le[j][k - 1]; for (int k = m; k > 0; k--) if (a[j][k] == i - 1) ri[j][k] = k; else ri[j][k] = ri[j][k + 1]; } int t; t = head[i]; while (t > 0) { int x, y; x = X[t]; y = Y[t]; for (int j = 1; j <= n; j++) { if (le[j][y] > -1 && (r[j][le[j][y]] + abs(j - x) + abs(le[j][y] - y) < r[x][y])) r[x][y] = r[j][le[j][y]] + abs(j - x) + abs(le[j][y] - y); if (ri[j][y] > -1 && (r[j][ri[j][y]] + abs(j - x) + abs(ri[j][y] - y) < r[x][y])) r[x][y] = r[j][ri[j][y]] + abs(j - x) + abs(ri[j][y] - y); } if (i == p) cout << r[x][y]; t = link[t]; } } void solve2(int i) { int t, t2, x, x2, y, y2; t = head[i]; while (t > 0) { x = X[t]; y = Y[t]; t2 = head[i - 1]; while (t2 > 0) { x2 = X[t2]; y2 = Y[t2]; if (r[x2][y2] + abs(x - x2) + abs(y - y2) < r[x][y]) r[x][y] = r[x2][y2] + abs(x - x2) + abs(y - y2); t2 = link[t2]; } if (i == p) cout << r[x][y]; t = link[t]; } } int main() { scanf("%d%d%d", &n, &m, &p); if (p == 1) { cout << 0; return 0; } for (int i = 1; i <= p; i++) head[i] = 0; for (int i = 1; i <= p; i++) Co[i] = 0; long long P = 0, MaxC = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); Co[a[i][j]]++; P++; X[P] = i; Y[P] = j; W[P] = a[i][j]; link[P] = head[W[P]]; head[W[P]] = P; } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == 1) r[i][j] = i + j - 2; else r[i][j] = vc; for (int i = 2; i <= p; i++) if (Co[i] * Co[i - 1] >= n * m) solve1(i); else solve2(i); return 0; } ```
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > adj[200005]; int dist[305][305], arr[305][305], n, m, di[305][305]; queue<pair<int, int> > q; vector<pair<int, pair<int, int> > > v; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; int distValue(pair<int, int> p1, pair<int, int> p2) { return abs(p1.first - p2.first) + abs(p1.second - p2.second); } bool valid(int x, int y) { return (x >= 1 && x <= n && y >= 1 && y <= m); } int main() { int k, i, j, p, X, Y; scanf("%d %d %d", &n, &m, &p); for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { dist[i][j] = 2000000200; } } for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { scanf("%d", &arr[i][j]); if (arr[i][j] == p) { X = i; Y = j; } if (arr[i][j] == 1) { dist[i][j] = (i + j - 2); } adj[arr[i][j]].push_back(make_pair(i, j)); } } for (i = 2; i <= p; i++) { int curr = adj[i].size(), pre = adj[i - 1].size(); if (curr * pre <= n * m) { for (auto p1 : adj[i - 1]) { for (auto p2 : adj[i]) { dist[p2.first][p2.second] = min(dist[p2.first][p2.second], dist[p1.first][p1.second] + distValue(p1, p2)); } } } else { v.clear(); for (j = 1; j <= n; j++) { for (k = 1; k <= m; k++) { di[j][k] = 2000000200; } } for (auto p1 : adj[i - 1]) { v.push_back(make_pair(dist[p1.first][p1.second], p1)); di[p1.first][p1.second] = dist[p1.first][p1.second]; } sort(v.begin(), v.end()); int pos = 1; q.push(v[0].second); while (!q.empty() || pos < v.size()) { if (q.empty()) { q.push(v[pos].second); pos++; } pair<int, int> p1 = q.front(); q.pop(); while (pos < v.size() && v[pos].first <= di[p1.first][p1.second]) { q.push(v[pos].second); pos++; } for (j = 0; j < 4; j++) { if (valid(p1.first + dir[j][0], p1.second + dir[j][1]) && di[p1.first + dir[j][0]][p1.second + dir[j][1]] > (di[p1.first][p1.second] + 1)) { di[p1.first + dir[j][0]][p1.second + dir[j][1]] = di[p1.first][p1.second] + 1; q.push(make_pair(p1.first + dir[j][0], p1.second + dir[j][1])); } } } for (auto p1 : adj[i]) { dist[p1.first][p1.second] = di[p1.first][p1.second]; } } } printf("%d\n", dist[X][Y]); 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; vector<pair<int, int> > adj[200005]; int dist[305][305], arr[305][305], n, m, di[305][305]; queue<pair<int, int> > q; vector<pair<int, pair<int, int> > > v; int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; int distValue(pair<int, int> p1, pair<int, int> p2) { return abs(p1.first - p2.first) + abs(p1.second - p2.second); } bool valid(int x, int y) { return (x >= 1 && x <= n && y >= 1 && y <= m); } int main() { int k, i, j, p, X, Y; scanf("%d %d %d", &n, &m, &p); for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { dist[i][j] = 2000000200; } } for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { scanf("%d", &arr[i][j]); if (arr[i][j] == p) { X = i; Y = j; } if (arr[i][j] == 1) { dist[i][j] = (i + j - 2); } adj[arr[i][j]].push_back(make_pair(i, j)); } } for (i = 2; i <= p; i++) { int curr = adj[i].size(), pre = adj[i - 1].size(); if (curr * pre <= n * m) { for (auto p1 : adj[i - 1]) { for (auto p2 : adj[i]) { dist[p2.first][p2.second] = min(dist[p2.first][p2.second], dist[p1.first][p1.second] + distValue(p1, p2)); } } } else { v.clear(); for (j = 1; j <= n; j++) { for (k = 1; k <= m; k++) { di[j][k] = 2000000200; } } for (auto p1 : adj[i - 1]) { v.push_back(make_pair(dist[p1.first][p1.second], p1)); di[p1.first][p1.second] = dist[p1.first][p1.second]; } sort(v.begin(), v.end()); int pos = 1; q.push(v[0].second); while (!q.empty() || pos < v.size()) { if (q.empty()) { q.push(v[pos].second); pos++; } pair<int, int> p1 = q.front(); q.pop(); while (pos < v.size() && v[pos].first <= di[p1.first][p1.second]) { q.push(v[pos].second); pos++; } for (j = 0; j < 4; j++) { if (valid(p1.first + dir[j][0], p1.second + dir[j][1]) && di[p1.first + dir[j][0]][p1.second + dir[j][1]] > (di[p1.first][p1.second] + 1)) { di[p1.first + dir[j][0]][p1.second + dir[j][1]] = di[p1.first][p1.second] + 1; q.push(make_pair(p1.first + dir[j][0], p1.second + dir[j][1])); } } } for (auto p1 : adj[i]) { dist[p1.first][p1.second] = di[p1.first][p1.second]; } } } printf("%d\n", dist[X][Y]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; const long long INF = 1e18; const int MAXN = 2e5 + 5; const int MAXM = 9e4 + 500; const int N = 300 + 10; const double EPS = 1e-5; int i, j, d; int n, k, m, p; int a[N][N], dp[2][N][N], last[N][N]; vector<pair<int, int> > grid[MAXM]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m >> p; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { cin >> a[i][j]; grid[a[i][j]].push_back({i, j}); } } int ans = 1e9; for (int now = 1; now <= p; now++) { for (auto g : grid[now]) { int first = g.first; int second = g.second; int dist = 1e9; for (i = 1; i <= n; i++) { if (last[i][second] == now - 1) dist = min(dist, dp[1][i][second] + abs(first - i)); } dp[0][first][second] = (now == 1 ? abs(first - 1) + abs(second - 1) : dist); if (now == p) ans = min(ans, dist); } for (auto g : grid[now]) { int first = g.first; int second = g.second; for (i = 1; i <= m; i++) { if (last[first][i] < now || last[first][i] == now && dp[0][first][second] + abs(second - i) < dp[1][first][i]) { last[first][i] = now; dp[1][first][i] = dp[0][first][second] + abs(second - i); } } } } cout << 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; const int MOD = 1e9 + 7; const long long INF = 1e18; const int MAXN = 2e5 + 5; const int MAXM = 9e4 + 500; const int N = 300 + 10; const double EPS = 1e-5; int i, j, d; int n, k, m, p; int a[N][N], dp[2][N][N], last[N][N]; vector<pair<int, int> > grid[MAXM]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m >> p; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { cin >> a[i][j]; grid[a[i][j]].push_back({i, j}); } } int ans = 1e9; for (int now = 1; now <= p; now++) { for (auto g : grid[now]) { int first = g.first; int second = g.second; int dist = 1e9; for (i = 1; i <= n; i++) { if (last[i][second] == now - 1) dist = min(dist, dp[1][i][second] + abs(first - i)); } dp[0][first][second] = (now == 1 ? abs(first - 1) + abs(second - 1) : dist); if (now == p) ans = min(ans, dist); } for (auto g : grid[now]) { int first = g.first; int second = g.second; for (i = 1; i <= m; i++) { if (last[first][i] < now || last[first][i] == now && dp[0][first][second] + abs(second - i) < dp[1][first][i]) { last[first][i] = now; dp[1][first][i] = dp[0][first][second] + abs(second - i); } } } } cout << ans; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int inf = 111111111; void io() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cout.precision(15); } long long mulmod(long long a, long long b, long long m) { long long q = (long long)(((long double)a * (long double)b) / (long double)m); long long r = a * b - q * m; if (r > m) r %= m; if (r < 0) r += m; return r; } template <typename T> T mod(T a, T b) { while (a < 0) a += b; return a % b; } template <typename T> T power(T e, T n, T m) { T x = 1, p = e; while (n) { if (n & 1) x = mod(x * p, m); p = mod(p * p, m); n >>= 1; } return x; } template <typename T> T power(T e, T n) { T x = 1, p = e; while (n) { if (n & 1) x = x * p; p = p * p; n >>= 1; } return x; } template <typename T> T InverseEuler(T a, T m) { return (a == 1 ? 1 : power(a, m - 2, m)); } template <typename T> T gcd(T a, T b) { return __gcd(a, b); } template <typename T> T lcm(T a, T b) { return (a * (b / gcd(a, b))); } int exEuclid(int a, int b, int &x, int &y) { if (a == 0) { x = 0; y = 1; return b; } if (b == 0) { x = 1; y = 0; return a; } int x1, y1; int g = exEuclid(b % a, a, x1, y1); x = y1 - (b / a) * x1; y = x1; return g; } vector<pair<int, pair<int, int> > > pts[90005]; int main(int argc, char *argv[]) { io(); int n, m, p; int xx; cin >> n >> m >> p; for (__typeof(n) i = 1; i <= n; ++i) { for (__typeof(m) j = 1; j <= m; ++j) { cin >> xx; pts[xx].push_back(make_pair(1e9, make_pair(i, j))); } } for (__typeof((int)(pts[1].size()) - 1) i = 0; i <= (int)(pts[1].size()) - 1; ++i) { pts[1][i].first = pts[1][i].second.first - 1 + pts[1][i].second.second - 1; } for (__typeof(p) pp = 2; pp <= p; ++pp) { sort((pts[pp - 1]).begin(), (pts[pp - 1]).end()); for (__typeof((int)(pts[pp].size()) - 1) i = 0; i <= (int)(pts[pp].size()) - 1; ++i) { for (__typeof(min((int)(pts[pp - 1].size()), n + m - 1) - 1) j = 0; j <= min((int)(pts[pp - 1].size()), n + m - 1) - 1; ++j) { int d = abs(pts[pp][i].second.first - pts[pp - 1][j].second.first) + abs(pts[pp][i].second.second - pts[pp - 1][j].second.second); pts[pp][i].first = min(pts[pp][i].first, pts[pp - 1][j].first + d); } } } cout << pts[p][0].first << '\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; const int inf = 111111111; void io() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cout.precision(15); } long long mulmod(long long a, long long b, long long m) { long long q = (long long)(((long double)a * (long double)b) / (long double)m); long long r = a * b - q * m; if (r > m) r %= m; if (r < 0) r += m; return r; } template <typename T> T mod(T a, T b) { while (a < 0) a += b; return a % b; } template <typename T> T power(T e, T n, T m) { T x = 1, p = e; while (n) { if (n & 1) x = mod(x * p, m); p = mod(p * p, m); n >>= 1; } return x; } template <typename T> T power(T e, T n) { T x = 1, p = e; while (n) { if (n & 1) x = x * p; p = p * p; n >>= 1; } return x; } template <typename T> T InverseEuler(T a, T m) { return (a == 1 ? 1 : power(a, m - 2, m)); } template <typename T> T gcd(T a, T b) { return __gcd(a, b); } template <typename T> T lcm(T a, T b) { return (a * (b / gcd(a, b))); } int exEuclid(int a, int b, int &x, int &y) { if (a == 0) { x = 0; y = 1; return b; } if (b == 0) { x = 1; y = 0; return a; } int x1, y1; int g = exEuclid(b % a, a, x1, y1); x = y1 - (b / a) * x1; y = x1; return g; } vector<pair<int, pair<int, int> > > pts[90005]; int main(int argc, char *argv[]) { io(); int n, m, p; int xx; cin >> n >> m >> p; for (__typeof(n) i = 1; i <= n; ++i) { for (__typeof(m) j = 1; j <= m; ++j) { cin >> xx; pts[xx].push_back(make_pair(1e9, make_pair(i, j))); } } for (__typeof((int)(pts[1].size()) - 1) i = 0; i <= (int)(pts[1].size()) - 1; ++i) { pts[1][i].first = pts[1][i].second.first - 1 + pts[1][i].second.second - 1; } for (__typeof(p) pp = 2; pp <= p; ++pp) { sort((pts[pp - 1]).begin(), (pts[pp - 1]).end()); for (__typeof((int)(pts[pp].size()) - 1) i = 0; i <= (int)(pts[pp].size()) - 1; ++i) { for (__typeof(min((int)(pts[pp - 1].size()), n + m - 1) - 1) j = 0; j <= min((int)(pts[pp - 1].size()), n + m - 1) - 1; ++j) { int d = abs(pts[pp][i].second.first - pts[pp - 1][j].second.first) + abs(pts[pp][i].second.second - pts[pp - 1][j].second.second); pts[pp][i].first = min(pts[pp][i].first, pts[pp - 1][j].first + d); } } } cout << pts[p][0].first << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int Maxn = 305; const int dx[] = {1, -1, 0, 0}; const int dy[] = {0, 0, -1, 1}; template <class T> inline T Read(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; } template <class T> void clear(T& A) { while (!A.empty()) A.pop(); } inline int dist(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } struct node { int x, y, dis; node() {} node(int a, int b, int c) { x = a; y = b; dis = c; } bool operator<(const node& A) const { if (dis == A.dis) return x < A.x; return dis < A.dis; } }; vector<pair<int, int> > point[Maxn * Maxn]; int dp[Maxn][Maxn], n, m; const int INF = 1 << 30; int d[Maxn][Maxn]; void bfs(const int& nowkey, const int& curs, const int& lasts) { memset(d, -1, sizeof(d)); vector<node> lst; queue<node> q; lst.clear(); clear(q); for (int i = 0; i < lasts; ++i) { int _x = point[nowkey - 1][i].first, _y = point[nowkey - 1][i].second; lst.push_back(node(_x, _y, dp[_x][_y])); } sort(lst.begin(), lst.end()); int head = 0; q.push(lst[head++]); while (!q.empty()) { int nx = q.front().x, ny = q.front().y, nd = q.front().dis; q.pop(); while (head < lasts && lst[head].dis <= nd) q.push(lst[head++]); for (int i = 0; i < 4; ++i) { int _x = nx + dx[i], _y = ny + dy[i]; if (((_x) > 0 && (_x) <= (n)) && ((_y) > 0 && (_y) <= (m)) && !(~d[_x][_y])) { d[_x][_y] = nd + 1; q.push(node(_x, _y, d[_x][_y])); } } } for (int i = 0; i < curs; ++i) { int _x = point[nowkey][i].first, _y = point[nowkey][i].second; dp[_x][_y] = d[_x][_y]; } } int main() { int p, a; Read(n); Read(m); Read(p); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { Read(a); point[a].push_back(make_pair(i, j)); if (a == 1) { dp[i][j] = i + j - 2; } else { dp[i][j] = INF; } } for (int i = 2; i <= p; ++i) { int curs = point[i].size(); int lasts = point[i - 1].size(); if (curs * lasts <= n * m) { for (int j = 0; j < curs; ++j) { int nowx = point[i][j].first, nowy = point[i][j].second; for (int k = 0; k < lasts; ++k) { int lastx = point[i - 1][k].first, lasty = point[i - 1][k].second; dp[nowx][nowy] = min(dp[nowx][nowy], dp[lastx][lasty] + dist(nowx, nowy, lastx, lasty)); } } } else bfs(i, curs, lasts); } printf("%d", dp[point[p][0].first][point[p][0].second]); 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 Maxn = 305; const int dx[] = {1, -1, 0, 0}; const int dy[] = {0, 0, -1, 1}; template <class T> inline T Read(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; } template <class T> void clear(T& A) { while (!A.empty()) A.pop(); } inline int dist(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } struct node { int x, y, dis; node() {} node(int a, int b, int c) { x = a; y = b; dis = c; } bool operator<(const node& A) const { if (dis == A.dis) return x < A.x; return dis < A.dis; } }; vector<pair<int, int> > point[Maxn * Maxn]; int dp[Maxn][Maxn], n, m; const int INF = 1 << 30; int d[Maxn][Maxn]; void bfs(const int& nowkey, const int& curs, const int& lasts) { memset(d, -1, sizeof(d)); vector<node> lst; queue<node> q; lst.clear(); clear(q); for (int i = 0; i < lasts; ++i) { int _x = point[nowkey - 1][i].first, _y = point[nowkey - 1][i].second; lst.push_back(node(_x, _y, dp[_x][_y])); } sort(lst.begin(), lst.end()); int head = 0; q.push(lst[head++]); while (!q.empty()) { int nx = q.front().x, ny = q.front().y, nd = q.front().dis; q.pop(); while (head < lasts && lst[head].dis <= nd) q.push(lst[head++]); for (int i = 0; i < 4; ++i) { int _x = nx + dx[i], _y = ny + dy[i]; if (((_x) > 0 && (_x) <= (n)) && ((_y) > 0 && (_y) <= (m)) && !(~d[_x][_y])) { d[_x][_y] = nd + 1; q.push(node(_x, _y, d[_x][_y])); } } } for (int i = 0; i < curs; ++i) { int _x = point[nowkey][i].first, _y = point[nowkey][i].second; dp[_x][_y] = d[_x][_y]; } } int main() { int p, a; Read(n); Read(m); Read(p); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { Read(a); point[a].push_back(make_pair(i, j)); if (a == 1) { dp[i][j] = i + j - 2; } else { dp[i][j] = INF; } } for (int i = 2; i <= p; ++i) { int curs = point[i].size(); int lasts = point[i - 1].size(); if (curs * lasts <= n * m) { for (int j = 0; j < curs; ++j) { int nowx = point[i][j].first, nowy = point[i][j].second; for (int k = 0; k < lasts; ++k) { int lastx = point[i - 1][k].first, lasty = point[i - 1][k].second; dp[nowx][nowy] = min(dp[nowx][nowy], dp[lastx][lasty] + dist(nowx, nowy, lastx, lasty)); } } } else bfs(i, curs, lasts); } printf("%d", dp[point[p][0].first][point[p][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, p; int a[305][305]; int cdst[305][305]; vector<pair<int, int> > vv[305 * 305]; void solve1(vector<pair<int, int> > &v1, vector<pair<int, int> > &v2) { for (auto &i : v2) { for (auto &j : v1) { cdst[i.first][i.second] = min(cdst[i.first][i.second], cdst[j.first][j.second] + abs(j.second - i.second) + abs(j.first - i.first)); } } } int d[4][305][305]; void solve2(vector<pair<int, int> > &v1, vector<pair<int, int> > &v2) { memset(d, 0x3f, sizeof(d)); for (auto &i : v1) { for (int j = 0; j < 4; j++) { d[j][i.first][i.second] = cdst[i.first][i.second]; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { d[0][i][j] = min(d[0][i][j], d[0][i][j - 1] + 1); d[0][i][j] = min(d[0][i][j], d[0][i - 1][j] + 1); } } for (int i = 1; i <= n; i++) { for (int j = m; j; j--) { d[1][i][j] = min(d[1][i][j], d[1][i][j + 1] + 1); d[1][i][j] = min(d[1][i][j], d[1][i - 1][j] + 1); } } for (int i = n; i; i--) { for (int j = 1; j <= m; j++) { d[2][i][j] = min(d[2][i][j], d[2][i][j - 1] + 1); d[2][i][j] = min(d[2][i][j], d[2][i + 1][j] + 1); } } for (int i = n; i; i--) { for (int j = m; j; j--) { d[3][i][j] = min(d[3][i][j], d[3][i][j + 1] + 1); d[3][i][j] = min(d[3][i][j], d[3][i + 1][j] + 1); } } for (auto &i : v2) { for (int k = 0; k < 4; k++) { cdst[i.first][i.second] = min(cdst[i.first][i.second], d[k][i.first][i.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", &a[i][j]); vv[a[i][j]].push_back({i, j}); } } memset(cdst, 0x3f, sizeof(cdst)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == 1) cdst[i][j] = abs(i - 1) + abs(j - 1); } } for (int i = 2; i <= p; i++) { int cur_size = vv[i].size(); int pre_size = vv[i - 1].size(); if (pre_size * cur_size <= n * m) { solve1(vv[i - 1], vv[i]); } else { solve2(vv[i - 1], vv[i]); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == p) { printf("%d", cdst[i][j]); } } } 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 n, m, p; int a[305][305]; int cdst[305][305]; vector<pair<int, int> > vv[305 * 305]; void solve1(vector<pair<int, int> > &v1, vector<pair<int, int> > &v2) { for (auto &i : v2) { for (auto &j : v1) { cdst[i.first][i.second] = min(cdst[i.first][i.second], cdst[j.first][j.second] + abs(j.second - i.second) + abs(j.first - i.first)); } } } int d[4][305][305]; void solve2(vector<pair<int, int> > &v1, vector<pair<int, int> > &v2) { memset(d, 0x3f, sizeof(d)); for (auto &i : v1) { for (int j = 0; j < 4; j++) { d[j][i.first][i.second] = cdst[i.first][i.second]; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { d[0][i][j] = min(d[0][i][j], d[0][i][j - 1] + 1); d[0][i][j] = min(d[0][i][j], d[0][i - 1][j] + 1); } } for (int i = 1; i <= n; i++) { for (int j = m; j; j--) { d[1][i][j] = min(d[1][i][j], d[1][i][j + 1] + 1); d[1][i][j] = min(d[1][i][j], d[1][i - 1][j] + 1); } } for (int i = n; i; i--) { for (int j = 1; j <= m; j++) { d[2][i][j] = min(d[2][i][j], d[2][i][j - 1] + 1); d[2][i][j] = min(d[2][i][j], d[2][i + 1][j] + 1); } } for (int i = n; i; i--) { for (int j = m; j; j--) { d[3][i][j] = min(d[3][i][j], d[3][i][j + 1] + 1); d[3][i][j] = min(d[3][i][j], d[3][i + 1][j] + 1); } } for (auto &i : v2) { for (int k = 0; k < 4; k++) { cdst[i.first][i.second] = min(cdst[i.first][i.second], d[k][i.first][i.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", &a[i][j]); vv[a[i][j]].push_back({i, j}); } } memset(cdst, 0x3f, sizeof(cdst)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == 1) cdst[i][j] = abs(i - 1) + abs(j - 1); } } for (int i = 2; i <= p; i++) { int cur_size = vv[i].size(); int pre_size = vv[i - 1].size(); if (pre_size * cur_size <= n * m) { solve1(vv[i - 1], vv[i]); } else { solve2(vv[i - 1], vv[i]); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == p) { printf("%d", cdst[i][j]); } } } return 0; } ```
#include <bits/stdc++.h> using namespace std; vector<pair<pair<int, int>, int>> chests[90005]; inline int dist(pair<int, int> x, pair<int, int> y) { return abs(x.first - y.first) + abs(x.second - y.second); } bool v[305][305]; int a[305][305]; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; int main() { int n, m, p, x; scanf("%d %d %d", &n, &m, &p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &x); chests[x].push_back({{i, j}, 0}); } } chests[0].push_back({{1, 1}, 0}); for (int i = 1; i <= p; i++) { if (chests[i].size() >= 2000) { memset(v, 0, sizeof v); memset(a, 0, sizeof a); set<pair<int, pair<int, int>>> s; for (auto& x : chests[i - 1]) { s.insert({x.second, x.first}); } while (!s.empty()) { auto f = *s.begin(); s.erase(s.begin()); if (f.second.first <= 0 || f.second.first > n) continue; if (f.second.second <= 0 || f.second.second > m) continue; if (v[f.second.first][f.second.second]) continue; v[f.second.first][f.second.second] = true; a[f.second.first][f.second.second] = f.first; for (int i = 0; i < 4; i++) { s.insert( {f.first + 1, {f.second.first + dx[i], f.second.second + dy[i]}}); } } for (auto& x : chests[i]) { x.second = a[x.first.first][x.first.second]; } } else { for (auto& x : chests[i]) { x.second = 999999999; for (auto& y : chests[i - 1]) { x.second = min(x.second, y.second + dist(x.first, y.first)); } } } } printf("%d\n", chests[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; vector<pair<pair<int, int>, int>> chests[90005]; inline int dist(pair<int, int> x, pair<int, int> y) { return abs(x.first - y.first) + abs(x.second - y.second); } bool v[305][305]; int a[305][305]; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; int main() { int n, m, p, x; scanf("%d %d %d", &n, &m, &p); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &x); chests[x].push_back({{i, j}, 0}); } } chests[0].push_back({{1, 1}, 0}); for (int i = 1; i <= p; i++) { if (chests[i].size() >= 2000) { memset(v, 0, sizeof v); memset(a, 0, sizeof a); set<pair<int, pair<int, int>>> s; for (auto& x : chests[i - 1]) { s.insert({x.second, x.first}); } while (!s.empty()) { auto f = *s.begin(); s.erase(s.begin()); if (f.second.first <= 0 || f.second.first > n) continue; if (f.second.second <= 0 || f.second.second > m) continue; if (v[f.second.first][f.second.second]) continue; v[f.second.first][f.second.second] = true; a[f.second.first][f.second.second] = f.first; for (int i = 0; i < 4; i++) { s.insert( {f.first + 1, {f.second.first + dx[i], f.second.second + dy[i]}}); } } for (auto& x : chests[i]) { x.second = a[x.first.first][x.first.second]; } } else { for (auto& x : chests[i]) { x.second = 999999999; for (auto& y : chests[i - 1]) { x.second = min(x.second, y.second + dist(x.first, y.first)); } } } } printf("%d\n", chests[p][0].second); return 0; } ```
#include <bits/stdc++.h> using namespace std; const long double PI = 3.1415926535897932384626433832795; const long double EPS = 1e-11; int n, m, p; int a[310][310]; vector<pair<int, int> > v[90900]; int d[310][310]; int td[310][310]; queue<pair<int, int> > q; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; void bfs(int c) { for (int i = 0; i < (n); i++) for (int j = 0; j < (m); j++) { td[i][j] = 999999999; if (a[i][j] == c) { q.push(make_pair(i, j)); td[i][j] = d[i][j]; } } while (!q.empty()) { pair<int, int> ver = q.front(); q.pop(); for (int i = 0; i < (4); i++) { pair<int, int> v = make_pair(ver.first + dx[i], ver.second + dy[i]); if (v.first >= 0 && v.first < n && v.second >= 0 && v.second < m && td[v.first][v.second] > td[ver.first][ver.second] + 1) { td[v.first][v.second] = td[ver.first][ver.second] + 1; if (a[v.first][v.second] == c + 1) d[v.first][v.second] = td[v.first][v.second]; q.push(make_pair(v.first, v.second)); } } } } int main() { cin >> n >> m >> p; for (int i = 0; i < (n); i++) for (int j = 0; j < (m); j++) { cin >> a[i][j]; v[a[i][j]].push_back(make_pair(i, j)); d[i][j] = 999999999; if (a[i][j] == 1) d[i][j] = i + j; } for (int i = 1; i < p; i++) { if (v[i].size() * v[i + 1].size() > n * m) bfs(i); else { for (int j = 0; j < (v[i].size()); j++) for (int k = 0; k < (v[i + 1].size()); k++) d[v[i + 1][k].first][v[i + 1][k].second] = min(d[v[i + 1][k].first][v[i + 1][k].second], d[v[i][j].first][v[i][j].second] + abs(v[i][j].first - v[i + 1][k].first) + abs(v[i][j].second - v[i + 1][k].second)); } } int ans = 0; for (int i = 0; i < (n); i++) for (int j = 0; j < (m); j++) if (a[i][j] == p) cout << d[i][j]; 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 long double PI = 3.1415926535897932384626433832795; const long double EPS = 1e-11; int n, m, p; int a[310][310]; vector<pair<int, int> > v[90900]; int d[310][310]; int td[310][310]; queue<pair<int, int> > q; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; void bfs(int c) { for (int i = 0; i < (n); i++) for (int j = 0; j < (m); j++) { td[i][j] = 999999999; if (a[i][j] == c) { q.push(make_pair(i, j)); td[i][j] = d[i][j]; } } while (!q.empty()) { pair<int, int> ver = q.front(); q.pop(); for (int i = 0; i < (4); i++) { pair<int, int> v = make_pair(ver.first + dx[i], ver.second + dy[i]); if (v.first >= 0 && v.first < n && v.second >= 0 && v.second < m && td[v.first][v.second] > td[ver.first][ver.second] + 1) { td[v.first][v.second] = td[ver.first][ver.second] + 1; if (a[v.first][v.second] == c + 1) d[v.first][v.second] = td[v.first][v.second]; q.push(make_pair(v.first, v.second)); } } } } int main() { cin >> n >> m >> p; for (int i = 0; i < (n); i++) for (int j = 0; j < (m); j++) { cin >> a[i][j]; v[a[i][j]].push_back(make_pair(i, j)); d[i][j] = 999999999; if (a[i][j] == 1) d[i][j] = i + j; } for (int i = 1; i < p; i++) { if (v[i].size() * v[i + 1].size() > n * m) bfs(i); else { for (int j = 0; j < (v[i].size()); j++) for (int k = 0; k < (v[i + 1].size()); k++) d[v[i + 1][k].first][v[i + 1][k].second] = min(d[v[i + 1][k].first][v[i + 1][k].second], d[v[i][j].first][v[i][j].second] + abs(v[i][j].first - v[i + 1][k].first) + abs(v[i][j].second - v[i + 1][k].second)); } } int ans = 0; for (int i = 0; i < (n); i++) for (int j = 0; j < (m); j++) if (a[i][j] == p) cout << d[i][j]; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int inf = 1e9; int n, m, p; int a[305][305]; vector<pair<int, int> > v[90004]; int bit[5][305][305]; int dp[305][305]; void update0(int i, int j, int v, int t) { for (int x = i; x <= 300; x += (x & (-x))) { for (int y = j; y <= 300; y += (y & -y)) bit[0][x][y] = t ? max(bit[0][x][y], v) : min(bit[0][x][y], v); } } int query0(int i, int j) { int ret = inf; for (int x = i; x > 0; x -= (x & -x)) for (int y = j; y > 0; y -= (y & -y)) ret = min(ret, bit[0][x][y]); return ret; } void update1(int i, int j, int v, int t) { for (int x = i; x <= 300; x += x & -x) for (int y = j; y > 0; y -= y & -y) bit[1][x][y] = t ? max(bit[1][x][y], v) : min(bit[1][x][y], v); } int query1(int i, int j) { int ret = inf; for (int x = i; x > 0; x -= x & -x) for (int y = j; y <= 300; y += y & -y) ret = min(ret, bit[1][x][y]); return ret; } void update2(int i, int j, int v, int t) { for (int x = i; x > 0; x -= x & -x) for (int y = j; y <= 300; y += y & -y) bit[2][x][y] = t ? max(bit[2][x][y], v) : min(bit[2][x][y], v); } int query2(int i, int j) { int ret = inf; for (int x = i; x <= 300; x += x & -x) for (int y = j; y > 0; y -= y & -y) ret = min(ret, bit[2][x][y]); return ret; } void update3(int i, int j, int v, int t) { for (int x = i; x > 0; x -= x & -x) for (int y = j; y > 0; y -= y & -y) bit[3][x][y] = t ? max(bit[3][x][y], v) : min(bit[3][x][y], v); } int query3(int i, int j) { int ret = inf; for (int x = i; x <= 300; x += x & -x) for (int y = j; y <= 300; y += y & -y) ret = min(ret, bit[3][x][y]); return ret; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> a[i][j]; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { v[a[i][j]].push_back(make_pair(i, j)); } } for (int i = 0; i <= 3; i++) { for (int j = 0; j <= 300; j++) { for (int k = 0; k <= 300; k++) bit[i][j][k] = inf; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == 1) { dp[i][j] = i - 1 + j - 1; update0(i, j, dp[i][j] - i - j, 0); update1(i, j, dp[i][j] - i + j, 0); update2(i, j, dp[i][j] + i - j, 0); update3(i, j, dp[i][j] + i + j, 0); } } } for (int key = 2; key <= p; key++) { for (pair<int, int> p : v[key]) { int x = p.first, y = p.second; int q0 = query0(x, y); int q1 = query1(x, y); int q2 = query2(x, y); int q3 = query3(x, y); int dist = q0 + x + y; dist = min(dist, q1 + x - y); dist = min(dist, q2 - x + y); dist = min(dist, q3 - x - y); dp[x][y] = dist; } for (pair<int, int> p : v[key - 1]) { int x = p.first, y = p.second; update0(x, y, inf, 1); update1(x, y, inf, 1); update2(x, y, inf, 1); update3(x, y, inf, 1); } for (pair<int, int> p : v[key]) { int x = p.first, y = p.second; update0(x, y, dp[x][y] - x - y, 0); update1(x, y, dp[x][y] - x + y, 0); update2(x, y, dp[x][y] + x - y, 0); update3(x, y, dp[x][y] + x + y, 0); } } int x = v[p][0].first, y = v[p][0].second; cout << dp[x][y] << "\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; const int inf = 1e9; int n, m, p; int a[305][305]; vector<pair<int, int> > v[90004]; int bit[5][305][305]; int dp[305][305]; void update0(int i, int j, int v, int t) { for (int x = i; x <= 300; x += (x & (-x))) { for (int y = j; y <= 300; y += (y & -y)) bit[0][x][y] = t ? max(bit[0][x][y], v) : min(bit[0][x][y], v); } } int query0(int i, int j) { int ret = inf; for (int x = i; x > 0; x -= (x & -x)) for (int y = j; y > 0; y -= (y & -y)) ret = min(ret, bit[0][x][y]); return ret; } void update1(int i, int j, int v, int t) { for (int x = i; x <= 300; x += x & -x) for (int y = j; y > 0; y -= y & -y) bit[1][x][y] = t ? max(bit[1][x][y], v) : min(bit[1][x][y], v); } int query1(int i, int j) { int ret = inf; for (int x = i; x > 0; x -= x & -x) for (int y = j; y <= 300; y += y & -y) ret = min(ret, bit[1][x][y]); return ret; } void update2(int i, int j, int v, int t) { for (int x = i; x > 0; x -= x & -x) for (int y = j; y <= 300; y += y & -y) bit[2][x][y] = t ? max(bit[2][x][y], v) : min(bit[2][x][y], v); } int query2(int i, int j) { int ret = inf; for (int x = i; x <= 300; x += x & -x) for (int y = j; y > 0; y -= y & -y) ret = min(ret, bit[2][x][y]); return ret; } void update3(int i, int j, int v, int t) { for (int x = i; x > 0; x -= x & -x) for (int y = j; y > 0; y -= y & -y) bit[3][x][y] = t ? max(bit[3][x][y], v) : min(bit[3][x][y], v); } int query3(int i, int j) { int ret = inf; for (int x = i; x <= 300; x += x & -x) for (int y = j; y <= 300; y += y & -y) ret = min(ret, bit[3][x][y]); return ret; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m >> p; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> a[i][j]; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { v[a[i][j]].push_back(make_pair(i, j)); } } for (int i = 0; i <= 3; i++) { for (int j = 0; j <= 300; j++) { for (int k = 0; k <= 300; k++) bit[i][j][k] = inf; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == 1) { dp[i][j] = i - 1 + j - 1; update0(i, j, dp[i][j] - i - j, 0); update1(i, j, dp[i][j] - i + j, 0); update2(i, j, dp[i][j] + i - j, 0); update3(i, j, dp[i][j] + i + j, 0); } } } for (int key = 2; key <= p; key++) { for (pair<int, int> p : v[key]) { int x = p.first, y = p.second; int q0 = query0(x, y); int q1 = query1(x, y); int q2 = query2(x, y); int q3 = query3(x, y); int dist = q0 + x + y; dist = min(dist, q1 + x - y); dist = min(dist, q2 - x + y); dist = min(dist, q3 - x - y); dp[x][y] = dist; } for (pair<int, int> p : v[key - 1]) { int x = p.first, y = p.second; update0(x, y, inf, 1); update1(x, y, inf, 1); update2(x, y, inf, 1); update3(x, y, inf, 1); } for (pair<int, int> p : v[key]) { int x = p.first, y = p.second; update0(x, y, dp[x][y] - x - y, 0); update1(x, y, dp[x][y] - x + y, 0); update2(x, y, dp[x][y] + x - y, 0); update3(x, y, dp[x][y] + x + y, 0); } } int x = v[p][0].first, y = v[p][0].second; cout << dp[x][y] << "\n"; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 330; const int M = 4 * N; const int Inf = 1e8; int n, m, p; int a[N][N]; int Dp[N][N]; vector<pair<int, int> > Idx[N * N]; int Dist(pair<int, int> x, pair<int, int> y) { return abs(x.first - y.first) + abs(x.second - y.second); } struct SegTree { int Tree[M]; void Merge(int Node) { Tree[Node] = min(Tree[(Node << 1)], Tree[(Node << 1 | 1)]); } void Build(int Node = 1, int L = 1, int R = m) { if (L == R) return void(Tree[Node] = Inf); Build((Node << 1), L, ((L + R) >> 1)); Build((Node << 1 | 1), ((L + R) >> 1) + 1, R); Merge(Node); } void Update(int i, int x, int Node = 1, int L = 1, int R = m) { if (L == R) return void(Tree[Node] = min(Tree[Node], x)); if (i <= ((L + R) >> 1)) Update(i, x, (Node << 1), L, ((L + R) >> 1)); else Update(i, x, (Node << 1 | 1), ((L + R) >> 1) + 1, R); Merge(Node); } int Query(int i, int j, int Node = 1, int L = 1, int R = m) { if (j < L || R < i) return Inf; if (i <= L && R <= j) return Tree[Node]; return min(Query(i, j, (Node << 1), L, ((L + R) >> 1)), Query(i, j, (Node << 1 | 1), ((L + R) >> 1) + 1, R)); } }; SegTree myTree1; SegTree myTree2; int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf("%d", &a[i][j]), Idx[a[i][j]].emplace_back(i, j); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) Dp[i][j] = Inf; for (pair<int, int> x : Idx[p]) Dp[x.first][x.second] = 0; for (int x = p - 1; x > 0; x--) { vector<pair<int, int> > A(Idx[x].size() + Idx[x + 1].size()); merge(Idx[x].begin(), Idx[x].end(), Idx[x + 1].begin(), Idx[x + 1].end(), A.begin()); myTree1.Build(); myTree2.Build(); for (pair<int, int> y : A) { int i = y.first; int j = y.second; if (a[i][j] == x) { Dp[i][j] = min(Dp[i][j], i + j + myTree1.Query(1, j)); Dp[i][j] = min(Dp[i][j], i - j + myTree2.Query(j, m)); } else { myTree1.Update(j, -i - j + Dp[i][j]); myTree2.Update(j, -i + j + Dp[i][j]); } } myTree1.Build(); myTree2.Build(); reverse(A.begin(), A.end()); for (pair<int, int> y : A) { int i = y.first; int j = y.second; if (a[i][j] == x) { Dp[i][j] = min(Dp[i][j], -i + j + myTree1.Query(1, j)); Dp[i][j] = min(Dp[i][j], -i - j + myTree2.Query(j, m)); } else { myTree1.Update(j, i - j + Dp[i][j]); myTree2.Update(j, i + j + Dp[i][j]); } } } int Ans = Inf; for (pair<int, int> x : Idx[1]) Ans = min(Ans, Dist(pair<int, int>(1, 1), x) + Dp[x.first][x.second]); cout << Ans << 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 int N = 330; const int M = 4 * N; const int Inf = 1e8; int n, m, p; int a[N][N]; int Dp[N][N]; vector<pair<int, int> > Idx[N * N]; int Dist(pair<int, int> x, pair<int, int> y) { return abs(x.first - y.first) + abs(x.second - y.second); } struct SegTree { int Tree[M]; void Merge(int Node) { Tree[Node] = min(Tree[(Node << 1)], Tree[(Node << 1 | 1)]); } void Build(int Node = 1, int L = 1, int R = m) { if (L == R) return void(Tree[Node] = Inf); Build((Node << 1), L, ((L + R) >> 1)); Build((Node << 1 | 1), ((L + R) >> 1) + 1, R); Merge(Node); } void Update(int i, int x, int Node = 1, int L = 1, int R = m) { if (L == R) return void(Tree[Node] = min(Tree[Node], x)); if (i <= ((L + R) >> 1)) Update(i, x, (Node << 1), L, ((L + R) >> 1)); else Update(i, x, (Node << 1 | 1), ((L + R) >> 1) + 1, R); Merge(Node); } int Query(int i, int j, int Node = 1, int L = 1, int R = m) { if (j < L || R < i) return Inf; if (i <= L && R <= j) return Tree[Node]; return min(Query(i, j, (Node << 1), L, ((L + R) >> 1)), Query(i, j, (Node << 1 | 1), ((L + R) >> 1) + 1, R)); } }; SegTree myTree1; SegTree myTree2; int main() { cin >> n >> m >> p; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf("%d", &a[i][j]), Idx[a[i][j]].emplace_back(i, j); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) Dp[i][j] = Inf; for (pair<int, int> x : Idx[p]) Dp[x.first][x.second] = 0; for (int x = p - 1; x > 0; x--) { vector<pair<int, int> > A(Idx[x].size() + Idx[x + 1].size()); merge(Idx[x].begin(), Idx[x].end(), Idx[x + 1].begin(), Idx[x + 1].end(), A.begin()); myTree1.Build(); myTree2.Build(); for (pair<int, int> y : A) { int i = y.first; int j = y.second; if (a[i][j] == x) { Dp[i][j] = min(Dp[i][j], i + j + myTree1.Query(1, j)); Dp[i][j] = min(Dp[i][j], i - j + myTree2.Query(j, m)); } else { myTree1.Update(j, -i - j + Dp[i][j]); myTree2.Update(j, -i + j + Dp[i][j]); } } myTree1.Build(); myTree2.Build(); reverse(A.begin(), A.end()); for (pair<int, int> y : A) { int i = y.first; int j = y.second; if (a[i][j] == x) { Dp[i][j] = min(Dp[i][j], -i + j + myTree1.Query(1, j)); Dp[i][j] = min(Dp[i][j], -i - j + myTree2.Query(j, m)); } else { myTree1.Update(j, i - j + Dp[i][j]); myTree2.Update(j, i + j + Dp[i][j]); } } } int Ans = Inf; for (pair<int, int> x : Idx[1]) Ans = min(Ans, Dist(pair<int, int>(1, 1), x) + Dp[x.first][x.second]); cout << Ans << endl; } ```
#include <bits/stdc++.h> using namespace std; struct node { int x, y, z; bool operator<(const node &_) const { return z < _.z; } }; const int MAXN = 300; const int INF = 1 << 30; const int stepx[4] = {1, 0, 0, -1}; const int stepy[4] = {0, 1, -1, 0}; int n, m, p; vector<pair<int, int> > V[(MAXN + 10) * (MAXN + 10)]; int f[MAXN + 10][MAXN + 10]; int graph[MAXN + 10][MAXN + 10]; int d[MAXN + 10][MAXN + 10]; queue<node> Q; vector<node> R; inline int dis(int xa, int ya, int xb, int yb) { return abs(xb - xa) + abs(yb - ya); } inline int legal(node &in) { if (in.x < 1 || in.x > n || in.y < 1 || in.y > m || d[in.x][in.y]) return 0; return 1; } inline int bfs(int now) { for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) d[i][j] = 0; R.clear(); for (int i = 0; i < V[now - 1].size(); i++) R.push_back((node){V[now - 1][i].first, V[now - 1][i].second, f[V[now - 1][i].first][V[now - 1][i].second]}); sort(R.begin(), R.end()); d[R[0].x][R[0].y] = R[0].z; Q.push(R[0]); int instack = 0; while (!Q.empty()) { node &head = Q.front(); Q.pop(); while (instack + 1 < R.size() && R[instack + 1].z <= head.z) { instack++; if (d[R[instack].x][R[instack].y] != 0) continue; d[R[instack].x][R[instack].y] = R[instack].z; Q.push(R[instack]); } for (int i = 0; i < 4; i++) { node tempn = head; tempn.x += stepx[i]; tempn.y += stepy[i]; tempn.z++; if (!legal(tempn)) continue; d[tempn.x][tempn.y] = tempn.z; Q.push(tempn); } } return 0; } int read(void) { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int tempa; scanf("%d", &tempa); graph[i][j] = tempa; V[tempa].push_back(make_pair(i, j)); if (tempa == 1) f[i][j] = dis(1, 1, i, j); else f[i][j] = INF; } return 0; } int init(void) { return 0; } int solve(void) { for (int i = 2; i <= p; i++) if (V[i].size() * V[i - 1].size() < n * m) for (int j = 0; j < V[i].size(); j++) for (int k = 0; k < V[i - 1].size(); k++) f[V[i][j].first][V[i][j].second] = min(f[V[i][j].first][V[i][j].second], f[V[i - 1][k].first][V[i - 1][k].second] + dis(V[i - 1][k].first, V[i - 1][k].second, V[i][j].first, V[i][j].second)); else { bfs(i); for (int j = 0; j < V[i].size(); j++) f[V[i][j].first][V[i][j].second] = d[V[i][j].first][V[i][j].second]; } printf("%d\n", f[V[p][0].first][V[p][0].second]); return 0; } int main(void) { read(); 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; struct node { int x, y, z; bool operator<(const node &_) const { return z < _.z; } }; const int MAXN = 300; const int INF = 1 << 30; const int stepx[4] = {1, 0, 0, -1}; const int stepy[4] = {0, 1, -1, 0}; int n, m, p; vector<pair<int, int> > V[(MAXN + 10) * (MAXN + 10)]; int f[MAXN + 10][MAXN + 10]; int graph[MAXN + 10][MAXN + 10]; int d[MAXN + 10][MAXN + 10]; queue<node> Q; vector<node> R; inline int dis(int xa, int ya, int xb, int yb) { return abs(xb - xa) + abs(yb - ya); } inline int legal(node &in) { if (in.x < 1 || in.x > n || in.y < 1 || in.y > m || d[in.x][in.y]) return 0; return 1; } inline int bfs(int now) { for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) d[i][j] = 0; R.clear(); for (int i = 0; i < V[now - 1].size(); i++) R.push_back((node){V[now - 1][i].first, V[now - 1][i].second, f[V[now - 1][i].first][V[now - 1][i].second]}); sort(R.begin(), R.end()); d[R[0].x][R[0].y] = R[0].z; Q.push(R[0]); int instack = 0; while (!Q.empty()) { node &head = Q.front(); Q.pop(); while (instack + 1 < R.size() && R[instack + 1].z <= head.z) { instack++; if (d[R[instack].x][R[instack].y] != 0) continue; d[R[instack].x][R[instack].y] = R[instack].z; Q.push(R[instack]); } for (int i = 0; i < 4; i++) { node tempn = head; tempn.x += stepx[i]; tempn.y += stepy[i]; tempn.z++; if (!legal(tempn)) continue; d[tempn.x][tempn.y] = tempn.z; Q.push(tempn); } } return 0; } int read(void) { scanf("%d%d%d", &n, &m, &p); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int tempa; scanf("%d", &tempa); graph[i][j] = tempa; V[tempa].push_back(make_pair(i, j)); if (tempa == 1) f[i][j] = dis(1, 1, i, j); else f[i][j] = INF; } return 0; } int init(void) { return 0; } int solve(void) { for (int i = 2; i <= p; i++) if (V[i].size() * V[i - 1].size() < n * m) for (int j = 0; j < V[i].size(); j++) for (int k = 0; k < V[i - 1].size(); k++) f[V[i][j].first][V[i][j].second] = min(f[V[i][j].first][V[i][j].second], f[V[i - 1][k].first][V[i - 1][k].second] + dis(V[i - 1][k].first, V[i - 1][k].second, V[i][j].first, V[i][j].second)); else { bfs(i); for (int j = 0; j < V[i].size(); j++) f[V[i][j].first][V[i][j].second] = d[V[i][j].first][V[i][j].second]; } printf("%d\n", f[V[p][0].first][V[p][0].second]); return 0; } int main(void) { read(); init(); solve(); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = (int)3e2 + 10; const int INF = (int)0x3f3f3f3f; struct Fenwick1D { int n, type; int ft[N]; Fenwick1D() {} Fenwick1D(int n, int type) : n(n), type(type) { for (int i = 1; i <= n; ++i) ft[i] = INF; } int Query(int i) { int ans = INF; if (type == 0) for (; i >= 1; i -= i & -i) ans = min(ans, ft[i]); if (type == 1) for (; i <= n; i += i & -i) ans = min(ans, ft[i]); return ans; } void Update(int i, int v) { if (type == 0) for (; i <= n; i += i & -i) ft[i] = min(ft[i], v); if (type == 1) for (; i >= 1; i -= i & -i) ft[i] = min(ft[i], v); } void Assign(int i, int v) { if (type == 0) for (; i <= n; i += i & -i) ft[i] = v; if (type == 1) for (; i >= 1; i -= i & -i) ft[i] = v; } }; struct Fenwick2D { int n, m, type1, type2; Fenwick1D ft[N]; Fenwick2D() {} Fenwick2D(int n, int m, int type1, int type2) : n(n), m(m), type1(type1), type2(type2) { for (int i = 1; i <= n; ++i) ft[i] = Fenwick1D(m, type2); } int Query(int i, int j) { int ans = INF; if (type1 == 0) for (; i >= 1; i -= i & -i) ans = min(ans, ft[i].Query(j)); if (type1 == 1) for (; i <= n; i += i & -i) ans = min(ans, ft[i].Query(j)); return ans; } void Update(int i, int j, int v) { if (type1 == 0) for (; i <= n; i += i & -i) ft[i].Update(j, v); if (type1 == 1) for (; i >= 1; i -= i & -i) ft[i].Update(j, v); } void Assign(int i, int j, int v) { if (type1 == 0) for (; i <= n; i += i & -i) ft[i].Assign(j, v); if (type1 == 1) for (; i >= 1; i -= i & -i) ft[i].Assign(j, v); } }; int n, m, p, a[N][N], d[N][N]; Fenwick2D T1, T2, T3, T4; vector<pair<int, int> > L[N * N]; void Update(int x, int y, int k) { T1.Update(x, y, k - (x + y)); T2.Update(x, y, k - (x - y)); T3.Update(x, y, k - (-x - y)); T4.Update(x, y, k - (-x + y)); } void Reset(int x, int y) { T1.Assign(x, y, INF); T2.Assign(x, y, INF); T3.Assign(x, y, INF); T4.Assign(x, y, INF); } 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]); T1 = Fenwick2D(n, m, 0, 0); T2 = Fenwick2D(n, m, 0, 1); T3 = Fenwick2D(n, m, 1, 1); T4 = Fenwick2D(n, m, 1, 0); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) L[a[i][j]].push_back(pair<int, int>(i, j)); for (int i = 0; i < (int)L[1].size(); ++i) { int x = L[1][i].first, y = L[1][i].second; d[x][y] = x + y - 2; Update(x, y, x + y - 2); } for (int v = 2; v <= p; ++v) { for (int i = 0; i < (int)L[v].size(); ++i) { int x = L[v][i].first, y = L[v][i].second; d[x][y] = INF; d[x][y] = min(d[x][y], (x + y) + T1.Query(x, y)); d[x][y] = min(d[x][y], (x - y) + T2.Query(x, y)); d[x][y] = min(d[x][y], (-x - y) + T3.Query(x, y)); d[x][y] = min(d[x][y], (-x + y) + T4.Query(x, y)); } for (int i = 0; i < (int)L[v - 1].size(); ++i) { int x = L[v - 1][i].first, y = L[v - 1][i].second; Reset(x, y); } for (int i = 0; i < (int)L[v].size(); ++i) { int x = L[v][i].first, y = L[v][i].second; Update(x, y, d[x][y]); } } int x = L[p][0].first, y = L[p][0].second; printf("%d", d[x][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> using namespace std; const int N = (int)3e2 + 10; const int INF = (int)0x3f3f3f3f; struct Fenwick1D { int n, type; int ft[N]; Fenwick1D() {} Fenwick1D(int n, int type) : n(n), type(type) { for (int i = 1; i <= n; ++i) ft[i] = INF; } int Query(int i) { int ans = INF; if (type == 0) for (; i >= 1; i -= i & -i) ans = min(ans, ft[i]); if (type == 1) for (; i <= n; i += i & -i) ans = min(ans, ft[i]); return ans; } void Update(int i, int v) { if (type == 0) for (; i <= n; i += i & -i) ft[i] = min(ft[i], v); if (type == 1) for (; i >= 1; i -= i & -i) ft[i] = min(ft[i], v); } void Assign(int i, int v) { if (type == 0) for (; i <= n; i += i & -i) ft[i] = v; if (type == 1) for (; i >= 1; i -= i & -i) ft[i] = v; } }; struct Fenwick2D { int n, m, type1, type2; Fenwick1D ft[N]; Fenwick2D() {} Fenwick2D(int n, int m, int type1, int type2) : n(n), m(m), type1(type1), type2(type2) { for (int i = 1; i <= n; ++i) ft[i] = Fenwick1D(m, type2); } int Query(int i, int j) { int ans = INF; if (type1 == 0) for (; i >= 1; i -= i & -i) ans = min(ans, ft[i].Query(j)); if (type1 == 1) for (; i <= n; i += i & -i) ans = min(ans, ft[i].Query(j)); return ans; } void Update(int i, int j, int v) { if (type1 == 0) for (; i <= n; i += i & -i) ft[i].Update(j, v); if (type1 == 1) for (; i >= 1; i -= i & -i) ft[i].Update(j, v); } void Assign(int i, int j, int v) { if (type1 == 0) for (; i <= n; i += i & -i) ft[i].Assign(j, v); if (type1 == 1) for (; i >= 1; i -= i & -i) ft[i].Assign(j, v); } }; int n, m, p, a[N][N], d[N][N]; Fenwick2D T1, T2, T3, T4; vector<pair<int, int> > L[N * N]; void Update(int x, int y, int k) { T1.Update(x, y, k - (x + y)); T2.Update(x, y, k - (x - y)); T3.Update(x, y, k - (-x - y)); T4.Update(x, y, k - (-x + y)); } void Reset(int x, int y) { T1.Assign(x, y, INF); T2.Assign(x, y, INF); T3.Assign(x, y, INF); T4.Assign(x, y, INF); } 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]); T1 = Fenwick2D(n, m, 0, 0); T2 = Fenwick2D(n, m, 0, 1); T3 = Fenwick2D(n, m, 1, 1); T4 = Fenwick2D(n, m, 1, 0); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) L[a[i][j]].push_back(pair<int, int>(i, j)); for (int i = 0; i < (int)L[1].size(); ++i) { int x = L[1][i].first, y = L[1][i].second; d[x][y] = x + y - 2; Update(x, y, x + y - 2); } for (int v = 2; v <= p; ++v) { for (int i = 0; i < (int)L[v].size(); ++i) { int x = L[v][i].first, y = L[v][i].second; d[x][y] = INF; d[x][y] = min(d[x][y], (x + y) + T1.Query(x, y)); d[x][y] = min(d[x][y], (x - y) + T2.Query(x, y)); d[x][y] = min(d[x][y], (-x - y) + T3.Query(x, y)); d[x][y] = min(d[x][y], (-x + y) + T4.Query(x, y)); } for (int i = 0; i < (int)L[v - 1].size(); ++i) { int x = L[v - 1][i].first, y = L[v - 1][i].second; Reset(x, y); } for (int i = 0; i < (int)L[v].size(); ++i) { int x = L[v][i].first, y = L[v][i].second; Update(x, y, d[x][y]); } } int x = L[p][0].first, y = L[p][0].second; printf("%d", d[x][y]); return 0; } ```
#include <bits/stdc++.h> using namespace std; template <typename T> T in() { char ch; T n = 0; bool ng = false; while (1) { ch = getchar(); if (ch == '-') { ng = true; ch = getchar(); break; } if (ch >= '0' && ch <= '9') break; } while (1) { n = n * 10 + (ch - '0'); ch = getchar(); if (ch < '0' || ch > '9') break; } return (ng ? -n : n); } template <typename T> inline T POW(T B, T P) { if (P == 0) return 1; if (P & 1) return B * POW(B, P - 1); else return (POW(B, P / 2) * POW(B, P / 2)); } template <typename T> inline T Gcd(T a, T b) { if (a < 0) return Gcd(-a, b); if (b < 0) return Gcd(a, -b); return (b == 0) ? a : Gcd(b, a % b); } template <typename T> inline T Lcm(T a, T b) { if (a < 0) return Lcm(-a, b); if (b < 0) return Lcm(a, -b); return a * (b / Gcd(a, b)); } long long Bigmod(long long base, long long power, long long MOD) { long long ret = 1; while (power) { if (power & 1) ret = (ret * base) % MOD; base = (base * base) % MOD; power >>= 1; } return ret; } bool isVowel(char ch) { ch = toupper(ch); if (ch == 'A' || ch == 'U' || ch == 'I' || ch == 'O' || ch == 'E') return true; return false; } long long ModInverse(long long number, long long MOD) { return Bigmod(number, MOD - 2, MOD); } bool isConst(char ch) { if (isalpha(ch) && !isVowel(ch)) return true; return false; } int toInt(string s) { int sm; stringstream second(s); second >> sm; return sm; } int a[303][303]; vector<pair<int, int> > A[300 * 300 + 12]; int Ds[303][303]; int Dst(pair<int, int> x, pair<int, int> y) { int ans = abs(x.first - y.first); ans += abs(x.second - y.second); return ans; } int main() { int n, m, k; n = in<int>(), m = in<int>(), k = in<int>(); for (int i = 1; i < n + 1; i++) for (int j = 1; j < m + 1; j++) { a[i][j] = in<int>(); A[a[i][j]].push_back(make_pair(i, j)); } if (k == 1) { printf("0\n"); return 0; } for (int i = 1; i < k + 1; i++) { random_shuffle(A[i].begin(), A[i].end()); } int now = 0; for (int i = 0; i <= 300; i++) { for (int j = 0; j <= 300; j++) { Ds[i][j] = 200000000; } } for (int i = 0; i < A[1].size(); i++) { int nw = Dst(make_pair(1, 1), A[now + 1][i]); int x = 1; int y = 1; int xx = A[now + 1][i].first; int yy = A[now + 1][i].second; Ds[xx][yy] = min(Ds[xx][yy], nw); } now++; while (now < k) { for (int i = 0; i < A[now].size() && i < 5000; i++) { for (int j = 0; j < A[now + 1].size() && j < 5000; j++) { int nw = Dst(A[now][i], A[now + 1][j]); int x = A[now][i].first; int y = A[now][i].second; int xx = A[now + 1][j].first; int yy = A[now + 1][j].second; Ds[xx][yy] = min(Ds[xx][yy], Ds[x][y] + nw); } } now++; } printf("%d\n", Ds[A[k][0].first][A[k][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; template <typename T> T in() { char ch; T n = 0; bool ng = false; while (1) { ch = getchar(); if (ch == '-') { ng = true; ch = getchar(); break; } if (ch >= '0' && ch <= '9') break; } while (1) { n = n * 10 + (ch - '0'); ch = getchar(); if (ch < '0' || ch > '9') break; } return (ng ? -n : n); } template <typename T> inline T POW(T B, T P) { if (P == 0) return 1; if (P & 1) return B * POW(B, P - 1); else return (POW(B, P / 2) * POW(B, P / 2)); } template <typename T> inline T Gcd(T a, T b) { if (a < 0) return Gcd(-a, b); if (b < 0) return Gcd(a, -b); return (b == 0) ? a : Gcd(b, a % b); } template <typename T> inline T Lcm(T a, T b) { if (a < 0) return Lcm(-a, b); if (b < 0) return Lcm(a, -b); return a * (b / Gcd(a, b)); } long long Bigmod(long long base, long long power, long long MOD) { long long ret = 1; while (power) { if (power & 1) ret = (ret * base) % MOD; base = (base * base) % MOD; power >>= 1; } return ret; } bool isVowel(char ch) { ch = toupper(ch); if (ch == 'A' || ch == 'U' || ch == 'I' || ch == 'O' || ch == 'E') return true; return false; } long long ModInverse(long long number, long long MOD) { return Bigmod(number, MOD - 2, MOD); } bool isConst(char ch) { if (isalpha(ch) && !isVowel(ch)) return true; return false; } int toInt(string s) { int sm; stringstream second(s); second >> sm; return sm; } int a[303][303]; vector<pair<int, int> > A[300 * 300 + 12]; int Ds[303][303]; int Dst(pair<int, int> x, pair<int, int> y) { int ans = abs(x.first - y.first); ans += abs(x.second - y.second); return ans; } int main() { int n, m, k; n = in<int>(), m = in<int>(), k = in<int>(); for (int i = 1; i < n + 1; i++) for (int j = 1; j < m + 1; j++) { a[i][j] = in<int>(); A[a[i][j]].push_back(make_pair(i, j)); } if (k == 1) { printf("0\n"); return 0; } for (int i = 1; i < k + 1; i++) { random_shuffle(A[i].begin(), A[i].end()); } int now = 0; for (int i = 0; i <= 300; i++) { for (int j = 0; j <= 300; j++) { Ds[i][j] = 200000000; } } for (int i = 0; i < A[1].size(); i++) { int nw = Dst(make_pair(1, 1), A[now + 1][i]); int x = 1; int y = 1; int xx = A[now + 1][i].first; int yy = A[now + 1][i].second; Ds[xx][yy] = min(Ds[xx][yy], nw); } now++; while (now < k) { for (int i = 0; i < A[now].size() && i < 5000; i++) { for (int j = 0; j < A[now + 1].size() && j < 5000; j++) { int nw = Dst(A[now][i], A[now + 1][j]); int x = A[now][i].first; int y = A[now][i].second; int xx = A[now + 1][j].first; int yy = A[now + 1][j].second; Ds[xx][yy] = min(Ds[xx][yy], Ds[x][y] + nw); } } now++; } printf("%d\n", Ds[A[k][0].first][A[k][0].second]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 300 + 10; int dp[maxn][maxn], vis[maxn][maxn], cnt[maxn * maxn], cn[maxn * maxn]; struct Poi { int x, y, p; Poi() {} Poi(int x, int y, int p) : x(x), y(y), p(p) {} bool operator<(const Poi &a) const { return p > a.p; } } poi[maxn * maxn]; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; int n, m, p, l; int cmp(const Poi &a, const Poi &b) { return a.p < b.p; } int dis(int a, int b) { return abs(poi[a].x - poi[b].x) + abs(poi[a].y - poi[b].y); } void bfs(int ti) { int x, y; memset(vis, 0x7f7f7f7f, sizeof(vis)); int tcnt = 0, len = n * m; queue<Poi> pq; for (int i = cn[ti - 1] - cnt[ti - 1]; i < cn[ti - 1]; ++i) { x = poi[i].x; y = poi[i].y; pq.push(Poi(x, y, dp[y][x])); } while (!pq.empty()) { Poi tp = pq.front(); pq.pop(); for (int i = 0; i < 4; ++i) { int tx = tp.x + dx[i], ty = tp.y + dy[i]; if (ty >= 1 && tx >= 1 && ty <= n && tx <= m && vis[ty][tx] > tp.p + 1) { vis[ty][tx] = tp.p + 1; tcnt++; pq.push(Poi(tx, ty, tp.p + 1)); } } } for (int j = cn[ti - 1]; j < cn[ti]; ++j) { x = poi[j].x; y = poi[j].y; dp[y][x] = vis[y][x]; } } int main() { l = 0; poi[l++] = Poi(1, 1, 0); cnt[0] = 1; memset(dp, 0x7f7f7f7f, sizeof(dp)); int x, y, tx, ty, i, j, z, t; scanf("%d%d%d", &n, &m, &p); for (i = 1; i <= n; ++i) for (j = 1; j <= m; ++j) { scanf("%d", &t); cnt[t]++; poi[l++] = Poi(j, i, t); } sort(poi, poi + l, cmp); cn[0] = 1; for (i = 1; i <= p; ++i) cn[i] = cn[i - 1] + cnt[i]; for (i = cn[0]; i < cn[1]; ++i) dp[poi[i].y][poi[i].x] = dis(0, i); for (i = 2; i <= p; ++i) { if (cnt[i] * cnt[i - 1] >= n * m) bfs(i); else { for (j = cn[i - 1]; j < cn[i]; ++j) { y = poi[j].y; x = poi[j].x; for (z = cn[i - 1] - cnt[i - 1]; z < cn[i - 1]; ++z) { ty = poi[z].y; tx = poi[z].x; dp[y][x] = min(dp[y][x], dp[ty][tx] + dis(j, z)); } } } } printf("%d\n", dp[poi[l - 1].y][poi[l - 1].x]); 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 = 300 + 10; int dp[maxn][maxn], vis[maxn][maxn], cnt[maxn * maxn], cn[maxn * maxn]; struct Poi { int x, y, p; Poi() {} Poi(int x, int y, int p) : x(x), y(y), p(p) {} bool operator<(const Poi &a) const { return p > a.p; } } poi[maxn * maxn]; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; int n, m, p, l; int cmp(const Poi &a, const Poi &b) { return a.p < b.p; } int dis(int a, int b) { return abs(poi[a].x - poi[b].x) + abs(poi[a].y - poi[b].y); } void bfs(int ti) { int x, y; memset(vis, 0x7f7f7f7f, sizeof(vis)); int tcnt = 0, len = n * m; queue<Poi> pq; for (int i = cn[ti - 1] - cnt[ti - 1]; i < cn[ti - 1]; ++i) { x = poi[i].x; y = poi[i].y; pq.push(Poi(x, y, dp[y][x])); } while (!pq.empty()) { Poi tp = pq.front(); pq.pop(); for (int i = 0; i < 4; ++i) { int tx = tp.x + dx[i], ty = tp.y + dy[i]; if (ty >= 1 && tx >= 1 && ty <= n && tx <= m && vis[ty][tx] > tp.p + 1) { vis[ty][tx] = tp.p + 1; tcnt++; pq.push(Poi(tx, ty, tp.p + 1)); } } } for (int j = cn[ti - 1]; j < cn[ti]; ++j) { x = poi[j].x; y = poi[j].y; dp[y][x] = vis[y][x]; } } int main() { l = 0; poi[l++] = Poi(1, 1, 0); cnt[0] = 1; memset(dp, 0x7f7f7f7f, sizeof(dp)); int x, y, tx, ty, i, j, z, t; scanf("%d%d%d", &n, &m, &p); for (i = 1; i <= n; ++i) for (j = 1; j <= m; ++j) { scanf("%d", &t); cnt[t]++; poi[l++] = Poi(j, i, t); } sort(poi, poi + l, cmp); cn[0] = 1; for (i = 1; i <= p; ++i) cn[i] = cn[i - 1] + cnt[i]; for (i = cn[0]; i < cn[1]; ++i) dp[poi[i].y][poi[i].x] = dis(0, i); for (i = 2; i <= p; ++i) { if (cnt[i] * cnt[i - 1] >= n * m) bfs(i); else { for (j = cn[i - 1]; j < cn[i]; ++j) { y = poi[j].y; x = poi[j].x; for (z = cn[i - 1] - cnt[i - 1]; z < cn[i - 1]; ++z) { ty = poi[z].y; tx = poi[z].x; dp[y][x] = min(dp[y][x], dp[ty][tx] + dis(j, z)); } } } } printf("%d\n", dp[poi[l - 1].y][poi[l - 1].x]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int kInf = numeric_limits<int>::max() / 32; struct Item { int x, value, left, right; }; void MarkLeft(vector<Item>& items) { int N = items.size(); items[0].left = items[0].value; for (int i = 1; i < N; ++i) { items[i].left = min(items[i].value, items[i - 1].left + items[i].x - items[i - 1].x); } } void MarkRight(vector<Item>& items) { int N = items.size(); items[N - 1].right = items[N - 1].value; for (int i = N - 2; i >= 0; --i) { items[i].right = min(items[i].value, items[i + 1].right + items[i + 1].x - items[i].x); } } int CalcImpact(int x, const vector<Item>& items) { Item to_search = {x, -1, -1, -1}; int i = lower_bound( items.begin(), items.end(), to_search, [](const Item& lhs, const Item& rhs) { return lhs.x < rhs.x; }) - items.begin(); if (i < items.size() && items[i].x == x) { return min(items[i].left, items[i].right); } int result = kInf; if (i > 0) { result = items[i - 1].left + abs(x - items[i - 1].x); } if (i < items.size()) { result = min(result, items[i].right + abs(x - items[i].x)); } return result; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int N, M, P; cin >> N >> M >> P; vector<map<int, vector<Item>>> items(P); for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { int a; cin >> a; --a; items[a][i].push_back({j, -1, -1, -1}); } } for (auto& a : items) { for (auto& p : a) { vector<Item>& v = p.second; sort(v.begin(), v.end(), [](const Item& lhs, const Item& rhs) { return lhs.x < rhs.x; }); } } { assert(items[P - 1].size() == 1); auto& i = items[P - 1].begin()->second; assert(i.size() == 1); i[0].value = i[0].left = i[0].right = 0; } for (int p = P - 2; p >= 0; --p) { auto& current = items[p]; const auto& next = items[p + 1]; for (auto& pr : current) { int x = pr.first; for (Item& v : pr.second) { int result = kInf; for (const auto& pr2 : next) { int x2 = pr2.first; const vector<Item>& v2 = pr2.second; result = min(result, abs(x2 - x) + CalcImpact(v.x, v2)); } v.value = result; } MarkLeft(pr.second); MarkRight(pr.second); } } int result = kInf; for (const auto& p : items[0]) { int x = p.first; for (const Item& i : p.second) { result = min(result, x + i.x + i.value); } } cout << result << '\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 kInf = numeric_limits<int>::max() / 32; struct Item { int x, value, left, right; }; void MarkLeft(vector<Item>& items) { int N = items.size(); items[0].left = items[0].value; for (int i = 1; i < N; ++i) { items[i].left = min(items[i].value, items[i - 1].left + items[i].x - items[i - 1].x); } } void MarkRight(vector<Item>& items) { int N = items.size(); items[N - 1].right = items[N - 1].value; for (int i = N - 2; i >= 0; --i) { items[i].right = min(items[i].value, items[i + 1].right + items[i + 1].x - items[i].x); } } int CalcImpact(int x, const vector<Item>& items) { Item to_search = {x, -1, -1, -1}; int i = lower_bound( items.begin(), items.end(), to_search, [](const Item& lhs, const Item& rhs) { return lhs.x < rhs.x; }) - items.begin(); if (i < items.size() && items[i].x == x) { return min(items[i].left, items[i].right); } int result = kInf; if (i > 0) { result = items[i - 1].left + abs(x - items[i - 1].x); } if (i < items.size()) { result = min(result, items[i].right + abs(x - items[i].x)); } return result; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int N, M, P; cin >> N >> M >> P; vector<map<int, vector<Item>>> items(P); for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { int a; cin >> a; --a; items[a][i].push_back({j, -1, -1, -1}); } } for (auto& a : items) { for (auto& p : a) { vector<Item>& v = p.second; sort(v.begin(), v.end(), [](const Item& lhs, const Item& rhs) { return lhs.x < rhs.x; }); } } { assert(items[P - 1].size() == 1); auto& i = items[P - 1].begin()->second; assert(i.size() == 1); i[0].value = i[0].left = i[0].right = 0; } for (int p = P - 2; p >= 0; --p) { auto& current = items[p]; const auto& next = items[p + 1]; for (auto& pr : current) { int x = pr.first; for (Item& v : pr.second) { int result = kInf; for (const auto& pr2 : next) { int x2 = pr2.first; const vector<Item>& v2 = pr2.second; result = min(result, abs(x2 - x) + CalcImpact(v.x, v2)); } v.value = result; } MarkLeft(pr.second); MarkRight(pr.second); } } int result = kInf; for (const auto& p : items[0]) { int x = p.first; for (const Item& i : p.second) { result = min(result, x + i.x + i.value); } } cout << result << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, a, b; int o[15]; int mixn = 9999; vector<int> V, V2; void dfs(int goal, int times) { if (times >= mixn) return; if (goal == n) { if (o[n] < 0) { V2 = V; mixn = times; } return; } for (int i = 0; i <= max(o[goal - 1] / b + 1, max(o[goal] / a + 1, o[goal + 1] / b + 1)); ++i) { if (o[goal - 1] < i * b) { o[goal - 1] -= i * b; o[goal] -= i * a; o[goal + 1] -= i * b; for (int j = 0; j < i; j++) V.push_back(goal); dfs(goal + 1, times + i); for (int j = 0; j < i; j++) V.pop_back(); o[goal - 1] += i * b; o[goal] += i * a; o[goal + 1] += i * b; } } } int main() { ios::sync_with_stdio(0); V2.clear(); cin >> n >> a >> b; for (int i = 1; i <= n; ++i) { cin >> o[i]; } dfs(2, 0); cout << mixn << endl; int len = V2.size(); for (int i = 0; i < len - 1; ++i) cout << V2[i] << " "; cout << V2[len - 1] << endl; return 0; }
### Prompt Create a solution in Cpp for the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, a, b; int o[15]; int mixn = 9999; vector<int> V, V2; void dfs(int goal, int times) { if (times >= mixn) return; if (goal == n) { if (o[n] < 0) { V2 = V; mixn = times; } return; } for (int i = 0; i <= max(o[goal - 1] / b + 1, max(o[goal] / a + 1, o[goal + 1] / b + 1)); ++i) { if (o[goal - 1] < i * b) { o[goal - 1] -= i * b; o[goal] -= i * a; o[goal + 1] -= i * b; for (int j = 0; j < i; j++) V.push_back(goal); dfs(goal + 1, times + i); for (int j = 0; j < i; j++) V.pop_back(); o[goal - 1] += i * b; o[goal] += i * a; o[goal + 1] += i * b; } } } int main() { ios::sync_with_stdio(0); V2.clear(); cin >> n >> a >> b; for (int i = 1; i <= n; ++i) { cin >> o[i]; } dfs(2, 0); cout << mixn << endl; int len = V2.size(); for (int i = 0; i < len - 1; ++i) cout << V2[i] << " "; cout << V2[len - 1] << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; int dp[15][20][20][20]; int h[20]; struct Node { int i, j, k, l; } pre[15][20][20][20]; int main() { int n, a, b; scanf("%d %d %d", &n, &a, &b); for (int i = 0; i < n; ++i) { scanf("%d", &h[i]); h[i]++; } memset(dp, 0x3f, sizeof(dp)); memset(pre, -1, sizeof(pre)); dp[1][h[0]][h[1]][h[2]] = 0; for (int i = 1; i < n - 1; ++i) for (int j = h[i - 1]; j >= 0; j--) for (int k = h[i]; k >= 0; k--) for (int l = h[i + 1]; l >= 0; l--) { if (dp[i][j][k][l] != 1061109567) { int d1 = max(0, j - b); int d2 = max(0, k - a); int d3 = max(0, l - b); if (dp[i][d1][d2][d3] > dp[i][j][k][l] + 1) { dp[i][d1][d2][d3] = dp[i][j][k][l] + 1; pre[i][d1][d2][d3].i = i; pre[i][d1][d2][d3].j = j; pre[i][d1][d2][d3].k = k; pre[i][d1][d2][d3].l = l; } if (d1 == 0 && dp[i + 1][d2][d3][h[i + 2]] > dp[i][j][k][l] + 1) { dp[i + 1][d2][d3][h[i + 2]] = dp[i][j][k][l] + 1; pre[i + 1][d2][d3][h[i + 2]].i = i; pre[i + 1][d2][d3][h[i + 2]].j = j; pre[i + 1][d2][d3][h[i + 2]].k = k; pre[i + 1][d2][d3][h[i + 2]].l = l; } if (j == 0 && dp[i + 1][k][l][h[i + 2]] > dp[i][j][k][l]) { dp[i + 1][k][l][h[i + 2]] = dp[i][j][k][l]; pre[i + 1][k][l][h[i + 2]] = pre[i][j][k][l]; } } } printf("%d\n", dp[n - 1][0][0][0]); Node tmp; tmp.i = n - 1; tmp.j = tmp.k = tmp.l = 0; while (!(tmp.i == 1 && tmp.j == h[0] && tmp.k == h[1] && tmp.l == h[2])) { tmp = pre[tmp.i][tmp.j][tmp.k][tmp.l]; printf("%d ", tmp.i + 1); } cout << endl; }
### Prompt Your challenge is to write a Cpp solution to the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int dp[15][20][20][20]; int h[20]; struct Node { int i, j, k, l; } pre[15][20][20][20]; int main() { int n, a, b; scanf("%d %d %d", &n, &a, &b); for (int i = 0; i < n; ++i) { scanf("%d", &h[i]); h[i]++; } memset(dp, 0x3f, sizeof(dp)); memset(pre, -1, sizeof(pre)); dp[1][h[0]][h[1]][h[2]] = 0; for (int i = 1; i < n - 1; ++i) for (int j = h[i - 1]; j >= 0; j--) for (int k = h[i]; k >= 0; k--) for (int l = h[i + 1]; l >= 0; l--) { if (dp[i][j][k][l] != 1061109567) { int d1 = max(0, j - b); int d2 = max(0, k - a); int d3 = max(0, l - b); if (dp[i][d1][d2][d3] > dp[i][j][k][l] + 1) { dp[i][d1][d2][d3] = dp[i][j][k][l] + 1; pre[i][d1][d2][d3].i = i; pre[i][d1][d2][d3].j = j; pre[i][d1][d2][d3].k = k; pre[i][d1][d2][d3].l = l; } if (d1 == 0 && dp[i + 1][d2][d3][h[i + 2]] > dp[i][j][k][l] + 1) { dp[i + 1][d2][d3][h[i + 2]] = dp[i][j][k][l] + 1; pre[i + 1][d2][d3][h[i + 2]].i = i; pre[i + 1][d2][d3][h[i + 2]].j = j; pre[i + 1][d2][d3][h[i + 2]].k = k; pre[i + 1][d2][d3][h[i + 2]].l = l; } if (j == 0 && dp[i + 1][k][l][h[i + 2]] > dp[i][j][k][l]) { dp[i + 1][k][l][h[i + 2]] = dp[i][j][k][l]; pre[i + 1][k][l][h[i + 2]] = pre[i][j][k][l]; } } } printf("%d\n", dp[n - 1][0][0][0]); Node tmp; tmp.i = n - 1; tmp.j = tmp.k = tmp.l = 0; while (!(tmp.i == 1 && tmp.j == h[0] && tmp.k == h[1] && tmp.l == h[2])) { tmp = pre[tmp.i][tmp.j][tmp.k][tmp.l]; printf("%d ", tmp.i + 1); } cout << endl; } ```
#include <bits/stdc++.h> using namespace std; int n, a, b, mx = 1e9, v[20], x[20], sav[20]; void bkt(int k, int ant, int eu, int nr) { int aux = max(eu / a + (eu >= 0), max(ant / b + (ant >= 0), v[k + 1] / b + 1)); if (k == n - 1) { x[n - 1] = aux; nr += aux; if (nr < mx) { mx = nr; memcpy(sav, x, sizeof(x)); } return; } if (nr > mx) return; for (int i = max(0, ant / b + (ant >= 0)); i <= aux; i++) { x[k] = i; bkt(k + 1, eu - i * a, v[k + 1] - i * b, nr + i); } } int main() { ios::sync_with_stdio(false); cin >> n >> a >> b; for (int i = 1; i <= n; i++) cin >> v[i]; bkt(2, v[1], v[2], 0); cout << mx << '\n'; for (int i = 2; i <= n - 1; i++) { for (int j = 1; j <= sav[i]; j++) cout << i << ' '; } cout << '\n'; return 0; }
### Prompt Develop a solution in Cpp to the problem described below: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, a, b, mx = 1e9, v[20], x[20], sav[20]; void bkt(int k, int ant, int eu, int nr) { int aux = max(eu / a + (eu >= 0), max(ant / b + (ant >= 0), v[k + 1] / b + 1)); if (k == n - 1) { x[n - 1] = aux; nr += aux; if (nr < mx) { mx = nr; memcpy(sav, x, sizeof(x)); } return; } if (nr > mx) return; for (int i = max(0, ant / b + (ant >= 0)); i <= aux; i++) { x[k] = i; bkt(k + 1, eu - i * a, v[k + 1] - i * b, nr + i); } } int main() { ios::sync_with_stdio(false); cin >> n >> a >> b; for (int i = 1; i <= n; i++) cin >> v[i]; bkt(2, v[1], v[2], 0); cout << mx << '\n'; for (int i = 2; i <= n - 1; i++) { for (int j = 1; j <= sav[i]; j++) cout << i << ' '; } cout << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return a ? gcd(b % a, a) : b; } int x[100]; stack<int> st; int n, a, b; int best = 100000; int nums[100], sum[100], best2[100]; bool z; void rec(int k) { if (k > n - 1) { bool z = true; int cnt = 0; for (int i = 2; i <= n - 1; i++) sum[i] = 0; for (int i = 2; i <= n - 1; i++) { cnt += nums[i]; sum[i - 1] += nums[i] * b; sum[i] += nums[i] * a; sum[i + 1] += nums[i] * b; } for (int i = 2; i <= n - 1; i++) { if (sum[i] <= x[i]) z = false; } if (z && best > cnt) { best = cnt; for (int i = 2; i <= n - 1; i++) best2[i] = nums[i]; } } else { int to; to = x[k] / a + 2; to = max(to, 0); for (int i = 0; i <= to; i++) { nums[k] = i; rec(k + 1); } } } int main() { cin.sync_with_stdio(0); cin.tie(0); cin >> n >> a >> b; for (int i = 1; i <= n; i++) cin >> x[i]; while (x[1] >= 0) { st.push(2); x[1] -= b; x[2] -= a; x[3] -= b; } while (x[n] >= 0) { st.push(n - 1); x[n - 2] -= b; x[n - 1] -= a; x[n] -= b; } rec(2); for (int i = 2; i <= n - 1; i++) { for (int j = 1; j <= best2[i]; j++) st.push(i); } cout << st.size() << "\n"; while (!st.empty()) { cout << st.top() << " "; st.pop(); } return 0; }
### Prompt In Cpp, your task is to solve the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return a ? gcd(b % a, a) : b; } int x[100]; stack<int> st; int n, a, b; int best = 100000; int nums[100], sum[100], best2[100]; bool z; void rec(int k) { if (k > n - 1) { bool z = true; int cnt = 0; for (int i = 2; i <= n - 1; i++) sum[i] = 0; for (int i = 2; i <= n - 1; i++) { cnt += nums[i]; sum[i - 1] += nums[i] * b; sum[i] += nums[i] * a; sum[i + 1] += nums[i] * b; } for (int i = 2; i <= n - 1; i++) { if (sum[i] <= x[i]) z = false; } if (z && best > cnt) { best = cnt; for (int i = 2; i <= n - 1; i++) best2[i] = nums[i]; } } else { int to; to = x[k] / a + 2; to = max(to, 0); for (int i = 0; i <= to; i++) { nums[k] = i; rec(k + 1); } } } int main() { cin.sync_with_stdio(0); cin.tie(0); cin >> n >> a >> b; for (int i = 1; i <= n; i++) cin >> x[i]; while (x[1] >= 0) { st.push(2); x[1] -= b; x[2] -= a; x[3] -= b; } while (x[n] >= 0) { st.push(n - 1); x[n - 2] -= b; x[n - 1] -= a; x[n] -= b; } rec(2); for (int i = 2; i <= n - 1; i++) { for (int j = 1; j <= best2[i]; j++) st.push(i); } cout << st.size() << "\n"; while (!st.empty()) { cout << st.top() << " "; st.pop(); } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 15, oo = 1 << 30; int N, a, b, Ans; int H[maxn], G[maxn], F[maxn]; int calc(int h, int b) { if (h <= 0) return 0; return h / b + (h % b != 0); } void Done1() { memcpy(G, H, sizeof(H)); for (int i = (2), _i = (N - 1); i <= _i; i++) { F[i] = calc(H[i - 1], b); H[i - 1] -= F[i] * b; H[i] -= F[i] * a; H[i + 1] -= F[i] * b; } F[N - 1] += calc(H[N], b); Ans = 0; for (int i = (2), _i = (N - 1); i <= _i; i++) Ans += F[i]; memcpy(H, G, sizeof(G)); memcpy(G, F, sizeof(F)); } void change(int i, int g) { H[i] -= g * a; H[i - 1] -= g * b; H[i + 1] -= g * b; F[i] += g; } void Prepare() { change(2, calc(H[1], b)); change(N - 1, calc(H[N], b)); } bool check_no(int i, int ret) { int sum = 0; for (int j = (1), _j = (N); j <= _j; j++) if (H[j] > 0) sum += H[j]; ret += calc(sum, a); return ret >= Ans; } void dfs(int i, int ret) { if (i == N) { if (ret < Ans) { Ans = ret; memcpy(G, F, sizeof(F)); } return; } int lo = calc(H[i - 1], b); int hi = max(lo, calc(H[i], a)); for (int g = (lo), _g = (hi); g <= _g; g++) { change(i, g); dfs(i + 1, ret + g); change(i, -g); } } int main() { for (; scanf("%d%d%d", &N, &a, &b) != EOF;) { for (int i = (1), _i = (N); i <= _i; i++) scanf("%d", &H[i]); for (int i = (1), _i = (N); i <= _i; i++) H[i]++; Done1(); for (int i = (2), _i = (N - 1); i <= _i; i++) F[i] = 0; Prepare(); dfs(2, F[2] + (N > 3 ? F[N - 1] : 0)); printf("%d\n", Ans); for (int i = (1), _i = (N); i <= _i; i++) { while (G[i]--) printf("%d ", i); } printf("\n"); } return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 15, oo = 1 << 30; int N, a, b, Ans; int H[maxn], G[maxn], F[maxn]; int calc(int h, int b) { if (h <= 0) return 0; return h / b + (h % b != 0); } void Done1() { memcpy(G, H, sizeof(H)); for (int i = (2), _i = (N - 1); i <= _i; i++) { F[i] = calc(H[i - 1], b); H[i - 1] -= F[i] * b; H[i] -= F[i] * a; H[i + 1] -= F[i] * b; } F[N - 1] += calc(H[N], b); Ans = 0; for (int i = (2), _i = (N - 1); i <= _i; i++) Ans += F[i]; memcpy(H, G, sizeof(G)); memcpy(G, F, sizeof(F)); } void change(int i, int g) { H[i] -= g * a; H[i - 1] -= g * b; H[i + 1] -= g * b; F[i] += g; } void Prepare() { change(2, calc(H[1], b)); change(N - 1, calc(H[N], b)); } bool check_no(int i, int ret) { int sum = 0; for (int j = (1), _j = (N); j <= _j; j++) if (H[j] > 0) sum += H[j]; ret += calc(sum, a); return ret >= Ans; } void dfs(int i, int ret) { if (i == N) { if (ret < Ans) { Ans = ret; memcpy(G, F, sizeof(F)); } return; } int lo = calc(H[i - 1], b); int hi = max(lo, calc(H[i], a)); for (int g = (lo), _g = (hi); g <= _g; g++) { change(i, g); dfs(i + 1, ret + g); change(i, -g); } } int main() { for (; scanf("%d%d%d", &N, &a, &b) != EOF;) { for (int i = (1), _i = (N); i <= _i; i++) scanf("%d", &H[i]); for (int i = (1), _i = (N); i <= _i; i++) H[i]++; Done1(); for (int i = (2), _i = (N - 1); i <= _i; i++) F[i] = 0; Prepare(); dfs(2, F[2] + (N > 3 ? F[N - 1] : 0)); printf("%d\n", Ans); for (int i = (1), _i = (N); i <= _i; i++) { while (G[i]--) printf("%d ", i); } printf("\n"); } return 0; } ```
#include <bits/stdc++.h> using namespace std; int a, b; vector<int> solve(vector<int> cur) { vector<int> res; bool mret = true; for (int i(0); i <= (((int)cur.size()) - 1); i++) if (cur[i] > 0) mret = false; if (mret) return res; if (((int)cur.size()) == 0) return res; if (((int)cur.size()) == 1) { if (cur[0] <= 0) return res; res.insert(res.end(), (cur[0] / a) + ((cur[0] % a) ? 1 : 0), 0); return res; } if (((int)cur.size()) == 2) { int temp0 = cur[0]; int temp1 = cur[1]; for (int i(0); i <= (cur[0] >= 0 ? ((cur[0] / a) + ((cur[0] % a) ? 1 : 0)) : 1 - 1); i++) { int k = 0; cur[0] -= i * a; while (cur[0] > 0 || cur[1] > 0) cur[1] -= a, cur[0] -= b, k++; if (res.empty() || ((int)res.size()) > k + i) { res.clear(); res.insert(res.end(), i, 0); res.insert(res.end(), k, 1); } cur[0] = temp0; cur[1] = temp1; } return res; } int cnt = ((int)cur.size()) / 2 - 1; int temp0 = cur[cnt], temp1 = cur[cnt + 1], temp2 = cur[cnt + 2]; int temps = ((((int)cur.size()) == 3) ? 0 : cur[cnt - 1]); for (int i(0); i <= (15 - 1); i++) { for (int j(0); j <= (15 - 1); j++) { cur[cnt] = temp0, cur[cnt + 1] = temp1, cur[cnt + 2] = temp2; if (((int)cur.size()) != 3) cur[cnt - 1] = temps; vector<int> do1(cur.begin(), cur.begin() + cnt); vector<int> do2(cur.begin() + cnt + 2, cur.end()); if (!do1.empty()) do1.back() -= i * b; do2[0] -= j * b; int s1 = 0, s2 = 0; cur[cnt] -= i * a + j * b; cur[cnt + 1] -= j * a + i * b; if (cur[cnt] > 0 && do1.empty()) continue; else if (!do1.empty() && cur[cnt] > 0) { while (cur[cnt] > 0) { cur[cnt] -= b, do1.back() -= a, s1++; if (((int)do1.size()) > 1) do1[((int)do1.size()) - 2] -= b; } } if (cur[cnt + 1] > 0) { while (cur[cnt + 1] > 0) { cur[cnt + 1] -= b, do2[0] -= a, s2++; if (((int)do2.size()) > 1) do2[1] -= b; } } vector<int> res1 = solve(do1); vector<int> res2 = solve(do2); if (res1.size() + res2.size() + s1 + s2 + i + j == 0) return res; if (res.empty() || ((int)res.size()) > res1.size() + res2.size() + s1 + s2 + i + j) { res.clear(); res.insert(res.end(), res1.begin(), res1.end()); for (int q(0); q <= (((int)res2.size()) - 1); q++) res2[q] += cnt + 2; res.insert(res.end(), res2.begin(), res2.end()); if (s1) res.insert(res.end(), s1, cnt - 1); if (s2) res.insert(res.end(), s2, cnt + 2); res.insert(res.end(), i, cnt); res.insert(res.end(), j, cnt + 1); } } } return res; } int main() { int n; scanf("%d%d%d", &n, &a, &b); vector<int> d(n); for (int i(0); i <= (n - 1); i++) scanf("%d", &d[i]); for (int i(0); i <= (n - 1); i++) d[i] += 1; vector<int> ans; while (d[0] > 0) { d[0] -= b; d[1] -= a; d[2] -= b; ans.push_back(1); } while (d.back() > 0) { d.back() -= b; d[((int)d.size()) - 2] -= a; d[((int)d.size()) - 3] -= b; ans.push_back(((int)d.size()) - 2); } d.erase(d.begin(), d.begin() + 1); d.erase(d.end() - 1, d.end()); vector<int> res = solve(d); for (int i(0); i <= (((int)res.size()) - 1); i++) res[i] += 1; res.insert(res.begin(), ans.begin(), ans.end()); printf("%d\n", ((int)res.size())); printf("%d", res[0] + 1); for (int i(0); i <= (((int)res.size()) - 1 - 1); i++) printf(" %d", res[i + 1] + 1); printf("\n"); return 0; }
### Prompt Generate a cpp solution to the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int a, b; vector<int> solve(vector<int> cur) { vector<int> res; bool mret = true; for (int i(0); i <= (((int)cur.size()) - 1); i++) if (cur[i] > 0) mret = false; if (mret) return res; if (((int)cur.size()) == 0) return res; if (((int)cur.size()) == 1) { if (cur[0] <= 0) return res; res.insert(res.end(), (cur[0] / a) + ((cur[0] % a) ? 1 : 0), 0); return res; } if (((int)cur.size()) == 2) { int temp0 = cur[0]; int temp1 = cur[1]; for (int i(0); i <= (cur[0] >= 0 ? ((cur[0] / a) + ((cur[0] % a) ? 1 : 0)) : 1 - 1); i++) { int k = 0; cur[0] -= i * a; while (cur[0] > 0 || cur[1] > 0) cur[1] -= a, cur[0] -= b, k++; if (res.empty() || ((int)res.size()) > k + i) { res.clear(); res.insert(res.end(), i, 0); res.insert(res.end(), k, 1); } cur[0] = temp0; cur[1] = temp1; } return res; } int cnt = ((int)cur.size()) / 2 - 1; int temp0 = cur[cnt], temp1 = cur[cnt + 1], temp2 = cur[cnt + 2]; int temps = ((((int)cur.size()) == 3) ? 0 : cur[cnt - 1]); for (int i(0); i <= (15 - 1); i++) { for (int j(0); j <= (15 - 1); j++) { cur[cnt] = temp0, cur[cnt + 1] = temp1, cur[cnt + 2] = temp2; if (((int)cur.size()) != 3) cur[cnt - 1] = temps; vector<int> do1(cur.begin(), cur.begin() + cnt); vector<int> do2(cur.begin() + cnt + 2, cur.end()); if (!do1.empty()) do1.back() -= i * b; do2[0] -= j * b; int s1 = 0, s2 = 0; cur[cnt] -= i * a + j * b; cur[cnt + 1] -= j * a + i * b; if (cur[cnt] > 0 && do1.empty()) continue; else if (!do1.empty() && cur[cnt] > 0) { while (cur[cnt] > 0) { cur[cnt] -= b, do1.back() -= a, s1++; if (((int)do1.size()) > 1) do1[((int)do1.size()) - 2] -= b; } } if (cur[cnt + 1] > 0) { while (cur[cnt + 1] > 0) { cur[cnt + 1] -= b, do2[0] -= a, s2++; if (((int)do2.size()) > 1) do2[1] -= b; } } vector<int> res1 = solve(do1); vector<int> res2 = solve(do2); if (res1.size() + res2.size() + s1 + s2 + i + j == 0) return res; if (res.empty() || ((int)res.size()) > res1.size() + res2.size() + s1 + s2 + i + j) { res.clear(); res.insert(res.end(), res1.begin(), res1.end()); for (int q(0); q <= (((int)res2.size()) - 1); q++) res2[q] += cnt + 2; res.insert(res.end(), res2.begin(), res2.end()); if (s1) res.insert(res.end(), s1, cnt - 1); if (s2) res.insert(res.end(), s2, cnt + 2); res.insert(res.end(), i, cnt); res.insert(res.end(), j, cnt + 1); } } } return res; } int main() { int n; scanf("%d%d%d", &n, &a, &b); vector<int> d(n); for (int i(0); i <= (n - 1); i++) scanf("%d", &d[i]); for (int i(0); i <= (n - 1); i++) d[i] += 1; vector<int> ans; while (d[0] > 0) { d[0] -= b; d[1] -= a; d[2] -= b; ans.push_back(1); } while (d.back() > 0) { d.back() -= b; d[((int)d.size()) - 2] -= a; d[((int)d.size()) - 3] -= b; ans.push_back(((int)d.size()) - 2); } d.erase(d.begin(), d.begin() + 1); d.erase(d.end() - 1, d.end()); vector<int> res = solve(d); for (int i(0); i <= (((int)res.size()) - 1); i++) res[i] += 1; res.insert(res.begin(), ans.begin(), ans.end()); printf("%d\n", ((int)res.size())); printf("%d", res[0] + 1); for (int i(0); i <= (((int)res.size()) - 1 - 1); i++) printf(" %d", res[i + 1] + 1); printf("\n"); return 0; } ```
#include <bits/stdc++.h> using namespace std; int dp[20][20][20]; int from[20][20][20]; int v[20]; int a, b, n; int main() { cin >> n >> a >> b; for (int i(0); i < n; i++) { cin >> v[i]; v[i]++; } n--; for (int i(0); i <= 16; i++) for (int j(0); j <= 16; j++) for (int k(0); k <= 16; k++) dp[i][j][k] = (1 << 30); for (int i(0); i <= 16; i++) for (int j(0); j <= 16; j++) if (i * a + j * b >= v[1] && i * b >= v[0]) dp[1][i][j] = i + j; for (int i(1); i < n - 1; i++) { for (int j(0); j <= 16; j++) { for (int k(0); k <= 16; k++) { if (dp[i][j][k] == (1 << 30)) continue; for (int altcv(0); altcv <= 16; altcv++) { if (k * a + (j + altcv) * b >= v[i + 1] && dp[i + 1][k][altcv] > dp[i][j][k] + altcv) { dp[i + 1][k][altcv] = dp[i][j][k] + altcv; from[i + 1][k][altcv] = j; } } } } } int bestj, bestk, bestans(1e9); for (int i(0); i <= 16; i++) if (dp[n - 1][i][0] < bestans && i * b >= v[n]) bestj = i, bestk = 0, bestans = dp[n - 1][i][0]; vector<int> hits(n + 2); for (int i(n - 1); i >= 1; i--) { hits[i] = bestj; int j = bestj; bestj = from[i][bestj][bestk]; bestk = j; } cout << bestans << '\n'; for (int i(1); i <= n; i++) while (hits[i]--) cout << i + 1 << ' '; cout << '\n'; return 0; }
### Prompt Create a solution in CPP for the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int dp[20][20][20]; int from[20][20][20]; int v[20]; int a, b, n; int main() { cin >> n >> a >> b; for (int i(0); i < n; i++) { cin >> v[i]; v[i]++; } n--; for (int i(0); i <= 16; i++) for (int j(0); j <= 16; j++) for (int k(0); k <= 16; k++) dp[i][j][k] = (1 << 30); for (int i(0); i <= 16; i++) for (int j(0); j <= 16; j++) if (i * a + j * b >= v[1] && i * b >= v[0]) dp[1][i][j] = i + j; for (int i(1); i < n - 1; i++) { for (int j(0); j <= 16; j++) { for (int k(0); k <= 16; k++) { if (dp[i][j][k] == (1 << 30)) continue; for (int altcv(0); altcv <= 16; altcv++) { if (k * a + (j + altcv) * b >= v[i + 1] && dp[i + 1][k][altcv] > dp[i][j][k] + altcv) { dp[i + 1][k][altcv] = dp[i][j][k] + altcv; from[i + 1][k][altcv] = j; } } } } } int bestj, bestk, bestans(1e9); for (int i(0); i <= 16; i++) if (dp[n - 1][i][0] < bestans && i * b >= v[n]) bestj = i, bestk = 0, bestans = dp[n - 1][i][0]; vector<int> hits(n + 2); for (int i(n - 1); i >= 1; i--) { hits[i] = bestj; int j = bestj; bestj = from[i][bestj][bestk]; bestk = j; } cout << bestans << '\n'; for (int i(1); i <= n; i++) while (hits[i]--) cout << i + 1 << ' '; cout << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; int a, b, n, i, ans, arr[20], res[100]; bool dfs(int d, int x, int l) { if (d == 0) { for (int i = 1; i <= n; i++) if (arr[i] >= 0) return false; return true; } if (arr[x] < 0) return dfs(d, x + 1, l); if (x == n) { arr[n] -= b; res[d] = n - 1; if (dfs(d - 1, x, l)) return true; arr[n] += b; } else for (int i = l; i <= x + 1; i++) if ((1 < i) && (i < n)) { res[d] = i; arr[i] -= a; arr[i - 1] -= b; arr[i + 1] -= b; if (dfs(d - 1, x, i)) return true; arr[i] += a; arr[i - 1] += b; arr[i + 1] += b; } return false; } int main() { scanf("%d %d %d", &n, &a, &b); for (int i = 1; i <= n; i++) scanf("%d", &arr[i]); for (ans = 1;; ans++) if (dfs(ans, 1, 2)) { printf("%d\n", ans); for (int i = ans; i > 0; i--) printf("%d ", res[i]); return 0; } }
### Prompt Generate a Cpp solution to the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int a, b, n, i, ans, arr[20], res[100]; bool dfs(int d, int x, int l) { if (d == 0) { for (int i = 1; i <= n; i++) if (arr[i] >= 0) return false; return true; } if (arr[x] < 0) return dfs(d, x + 1, l); if (x == n) { arr[n] -= b; res[d] = n - 1; if (dfs(d - 1, x, l)) return true; arr[n] += b; } else for (int i = l; i <= x + 1; i++) if ((1 < i) && (i < n)) { res[d] = i; arr[i] -= a; arr[i - 1] -= b; arr[i + 1] -= b; if (dfs(d - 1, x, i)) return true; arr[i] += a; arr[i - 1] += b; arr[i + 1] += b; } return false; } int main() { scanf("%d %d %d", &n, &a, &b); for (int i = 1; i <= n; i++) scanf("%d", &arr[i]); for (ans = 1;; ans++) if (dfs(ans, 1, 2)) { printf("%d\n", ans); for (int i = ans; i > 0; i--) printf("%d ", res[i]); return 0; } } ```
#include <bits/stdc++.h> using namespace std; int N, a, b; int arr[15]; int dp[2][20][20][20]; vector<pair<int, int> > path[2][20][20][20]; inline void update(int now, int i, int j, int k, int pre, int i2, int j2, int k2, int cnt, int pos) { if (dp[pre][i2][j2][k2] == -1) return; if (dp[now][i][j][k] == -1 || dp[now][i][j][k] > dp[pre][i2][j2][k2] + cnt) { dp[now][i][j][k] = dp[pre][i2][j2][k2] + cnt; path[now][i][j][k].clear(); for (pair<int, int> x : path[pre][i2][j2][k2]) path[now][i][j][k].emplace_back(x); if (cnt != 0) path[now][i][j][k].emplace_back(make_pair(pos, cnt)); } } int tem[20][20]; vector<pair<int, int> > tem_path[20][20]; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> N >> a >> b; for (int i = 1, val; i <= N; i++) cin >> val, arr[i] = val + 1; arr[N + 1] = 0; memset(dp[1], -1, sizeof dp[1]); dp[1][arr[1]][arr[2]][arr[3]] = 0; for (int i = 0; i <= 17; i++) for (int j = 0; j <= 17; j++) for (int k = 0; k <= 17; k++) { if (i != 0) update(1, i, j, k, 1, i - 1, j, k, 0, -1); if (j != 0) update(1, i, j, k, 1, i, j - 1, k, 0, -1); if (k != 0) update(1, i, j, k, 1, i, j, k - 1, 0, -1); } for (int idx = 2, now = 0, pre = 1; idx < N; idx++, now ^= 1, pre ^= 1) { memset(dp[now], -1, sizeof dp[now]); for (int i = 0; i <= 17; i++) for (int j = 0; j <= 17; j++) for (int k = 0; k <= 17; k++) for (int cnt = 0; cnt <= 16; cnt++) { int i2 = min(17, i + b * cnt), j2 = min(17, j + a * cnt), k2 = min(17, k + b * cnt); update(now, i, j, k, pre, i2, j2, k2, cnt, idx); } for (int j = 0; j <= 17; j++) for (int k = 0; k <= 17; k++) { tem_path[j][k].clear(); if (dp[now][0][j][k] == -1) tem[j][k] = -1; else { tem[j][k] = dp[now][0][j][k]; for (pair<int, int> x : path[now][0][j][k]) tem_path[j][k].emplace_back(x); } } for (int i = 0; i <= 17; i++) for (int j = 0; j <= 17; j++) for (int k = 0; k <= 17; k++) { if (k != arr[idx + 2]) dp[now][i][j][k] = -1; else { dp[now][i][j][k] = tem[i][j]; path[now][i][j][k].clear(); for (pair<int, int> x : tem_path[i][j]) path[now][i][j][k].emplace_back(x); } if (i != 0) update(now, i, j, k, now, i - 1, j, k, 0, -1); if (j != 0) update(now, i, j, k, now, i, j - 1, k, 0, -1); if (k != 0) update(now, i, j, k, now, i, j, k - 1, 0, -1); } } cout << dp[~N & 1][0][0][0] << endl; for (pair<int, int> now : path[~N & 1][0][0][0]) { int cnt = now.second; while (cnt--) cout << now.first << " "; } cout << endl; return 0; }
### Prompt Generate a CPP solution to the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int N, a, b; int arr[15]; int dp[2][20][20][20]; vector<pair<int, int> > path[2][20][20][20]; inline void update(int now, int i, int j, int k, int pre, int i2, int j2, int k2, int cnt, int pos) { if (dp[pre][i2][j2][k2] == -1) return; if (dp[now][i][j][k] == -1 || dp[now][i][j][k] > dp[pre][i2][j2][k2] + cnt) { dp[now][i][j][k] = dp[pre][i2][j2][k2] + cnt; path[now][i][j][k].clear(); for (pair<int, int> x : path[pre][i2][j2][k2]) path[now][i][j][k].emplace_back(x); if (cnt != 0) path[now][i][j][k].emplace_back(make_pair(pos, cnt)); } } int tem[20][20]; vector<pair<int, int> > tem_path[20][20]; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> N >> a >> b; for (int i = 1, val; i <= N; i++) cin >> val, arr[i] = val + 1; arr[N + 1] = 0; memset(dp[1], -1, sizeof dp[1]); dp[1][arr[1]][arr[2]][arr[3]] = 0; for (int i = 0; i <= 17; i++) for (int j = 0; j <= 17; j++) for (int k = 0; k <= 17; k++) { if (i != 0) update(1, i, j, k, 1, i - 1, j, k, 0, -1); if (j != 0) update(1, i, j, k, 1, i, j - 1, k, 0, -1); if (k != 0) update(1, i, j, k, 1, i, j, k - 1, 0, -1); } for (int idx = 2, now = 0, pre = 1; idx < N; idx++, now ^= 1, pre ^= 1) { memset(dp[now], -1, sizeof dp[now]); for (int i = 0; i <= 17; i++) for (int j = 0; j <= 17; j++) for (int k = 0; k <= 17; k++) for (int cnt = 0; cnt <= 16; cnt++) { int i2 = min(17, i + b * cnt), j2 = min(17, j + a * cnt), k2 = min(17, k + b * cnt); update(now, i, j, k, pre, i2, j2, k2, cnt, idx); } for (int j = 0; j <= 17; j++) for (int k = 0; k <= 17; k++) { tem_path[j][k].clear(); if (dp[now][0][j][k] == -1) tem[j][k] = -1; else { tem[j][k] = dp[now][0][j][k]; for (pair<int, int> x : path[now][0][j][k]) tem_path[j][k].emplace_back(x); } } for (int i = 0; i <= 17; i++) for (int j = 0; j <= 17; j++) for (int k = 0; k <= 17; k++) { if (k != arr[idx + 2]) dp[now][i][j][k] = -1; else { dp[now][i][j][k] = tem[i][j]; path[now][i][j][k].clear(); for (pair<int, int> x : tem_path[i][j]) path[now][i][j][k].emplace_back(x); } if (i != 0) update(now, i, j, k, now, i - 1, j, k, 0, -1); if (j != 0) update(now, i, j, k, now, i, j - 1, k, 0, -1); if (k != 0) update(now, i, j, k, now, i, j, k - 1, 0, -1); } } cout << dp[~N & 1][0][0][0] << endl; for (pair<int, int> now : path[~N & 1][0][0][0]) { int cnt = now.second; while (cnt--) cout << now.first << " "; } cout << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, a, b, h[20], f[20][20][20][20], g[20][20][20][20][5]; void update(int &f1, int f2, int p[5], int i, int j, int k, int l, int w) { if (f2 < f1) { f1 = f2; p[0] = w; p[1] = i; p[2] = j; p[3] = k; p[4] = l; } } int main() { cin >> n >> a >> b; memset(h, 0, sizeof h); for (int i = 0; i < n; i++) { scanf("%d", h + i); h[i]++; } memset(f, 0x3f, sizeof f); f[1][h[0]][h[1]][h[2]] = 0; memset(g, 0xff, sizeof g); for (int i = 1; i < n; i++) { for (int j = 16; j >= 0; j--) { for (int k = 16; k >= 0; k--) for (int l = 16; l >= 0; l--) { if (j == 0) update(f[i + 1][k][l][h[i + 2]], f[i][j][k][l], g[i + 1][k][l][h[i + 2]], g[i][j][k][l][1], g[i][j][k][l][2], g[i][j][k][l][3], g[i][j][k][l][4], g[i][j][k][l][0]); if (i != n - 1) { int j1 = j - b > 0 ? j - b : 0, k1 = k - a > 0 ? k - a : 0, l1 = l - b > 0 ? l - b : 0; if (j <= b) update(f[i + 1][k1][l1][h[i + 2]], f[i][j][k][l] + 1, g[i + 1][k1][l1][h[i + 2]], i, j, k, l, i); update(f[i][j1][k1][l1], f[i][j][k][l] + 1, g[i][j1][k1][l1], i, j, k, l, i); } if (i != 1) { int j1 = j - a > 0 ? j - a : 0, k1 = k - b > 0 ? k - b : 0; if (j <= a) update(f[i + 1][k1][l][h[i + 2]], f[i][j][k][l] + 1, g[i + 1][k1][l][h[i + 2]], i, j, k, l, i - 1); update(f[i][j1][k1][l], f[i][j][k][l] + 1, g[i][j1][k1][l], i, j, k, l, i - 1); } } } } cout << f[n - 1][0][0][0] << endl; int i = n - 1, j = 0, k = 0, l = 0; while (i != -1) { if (g[i][j][k][l][0] == -1) break; printf("%d ", g[i][j][k][l][0] + 1); int i1 = g[i][j][k][l][1], j1 = g[i][j][k][l][2], k1 = g[i][j][k][l][3], l1 = g[i][j][k][l][4]; i = i1, j = j1, k = k1, l = l1; } return 0; }
### Prompt In cpp, your task is to solve the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, a, b, h[20], f[20][20][20][20], g[20][20][20][20][5]; void update(int &f1, int f2, int p[5], int i, int j, int k, int l, int w) { if (f2 < f1) { f1 = f2; p[0] = w; p[1] = i; p[2] = j; p[3] = k; p[4] = l; } } int main() { cin >> n >> a >> b; memset(h, 0, sizeof h); for (int i = 0; i < n; i++) { scanf("%d", h + i); h[i]++; } memset(f, 0x3f, sizeof f); f[1][h[0]][h[1]][h[2]] = 0; memset(g, 0xff, sizeof g); for (int i = 1; i < n; i++) { for (int j = 16; j >= 0; j--) { for (int k = 16; k >= 0; k--) for (int l = 16; l >= 0; l--) { if (j == 0) update(f[i + 1][k][l][h[i + 2]], f[i][j][k][l], g[i + 1][k][l][h[i + 2]], g[i][j][k][l][1], g[i][j][k][l][2], g[i][j][k][l][3], g[i][j][k][l][4], g[i][j][k][l][0]); if (i != n - 1) { int j1 = j - b > 0 ? j - b : 0, k1 = k - a > 0 ? k - a : 0, l1 = l - b > 0 ? l - b : 0; if (j <= b) update(f[i + 1][k1][l1][h[i + 2]], f[i][j][k][l] + 1, g[i + 1][k1][l1][h[i + 2]], i, j, k, l, i); update(f[i][j1][k1][l1], f[i][j][k][l] + 1, g[i][j1][k1][l1], i, j, k, l, i); } if (i != 1) { int j1 = j - a > 0 ? j - a : 0, k1 = k - b > 0 ? k - b : 0; if (j <= a) update(f[i + 1][k1][l][h[i + 2]], f[i][j][k][l] + 1, g[i + 1][k1][l][h[i + 2]], i, j, k, l, i - 1); update(f[i][j1][k1][l], f[i][j][k][l] + 1, g[i][j1][k1][l], i, j, k, l, i - 1); } } } } cout << f[n - 1][0][0][0] << endl; int i = n - 1, j = 0, k = 0, l = 0; while (i != -1) { if (g[i][j][k][l][0] == -1) break; printf("%d ", g[i][j][k][l][0] + 1); int i1 = g[i][j][k][l][1], j1 = g[i][j][k][l][2], k1 = g[i][j][k][l][3], l1 = g[i][j][k][l][4]; i = i1, j = j1, k = k1, l = l1; } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; const int INF = 0x3f3f3f3f; namespace fastIO { bool IOerror = 0; inline char nc() { static char buf[100000], *p1 = buf + 100000, *pend = buf + 100000; if (p1 == pend) { p1 = buf; pend = buf + fread(buf, 1, 100000, stdin); if (pend == p1) { IOerror = 1; return -1; } } return *p1++; } inline bool blank(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; } inline bool read(int &x) { char ch; bool ne = false; while (blank(ch = nc())) ; if (IOerror) return false; if (ch == '-') ne = true, ch = nc(); for (x = ch - '0'; (ch = nc()) >= '0' && ch <= '9'; x = x * 10 + ch - '0') ; if (ne) x = -x; return true; } inline bool read(long long &x) { char ch; bool ne = false; while (blank(ch = nc())) ; if (IOerror) return false; if (ch == '-') ne = true, ch = nc(); for (x = ch - '0'; (ch = nc()) >= '0' && ch <= '9'; x = x * 10 + ch - '0') ; if (ne) x = -x; return true; } }; // namespace fastIO using namespace fastIO; const int N = 30; int h[N]; vector<char> cnt; vector<char> mem; int n; inline int check() { int tmp = max_element(h + 1, h + n - 1) - h; if (h[tmp] >= 0) return tmp; else return -1; } int a, b, ans; set<vector<char>> mp; void dfs(int pos) { if (mp.count(mem)) return; mp.insert(mem); int tmp = check(); if (tmp == -1) { if (ans > pos) cnt = mem, ans = pos; return; } int tt = 0; for (int i = 1; i < (n - 1); i++) { if (h[i] < 0 && h[i - 1] < 0) continue; h[i] -= a; h[i - 1] -= b; h[i + 1] -= b; mem[i]++; dfs(pos + 1); h[i] += a; h[i - 1] += b; h[i + 1] += b; mem[i]--; if (tt++ > 1) break; } } int main() { read(n), read(a), read(b); for (int i = 0; i < (n); i++) read(h[i]), cnt.push_back(0); if (n == 3) { cnt[1] = max((h[0] + b) / b, (h[2] + b) / b); h[1] -= cnt[1] * a; if (h[1] >= 0) cnt[1] += (h[1] + a) / a; ans = 0; for (int i = 1; i < (n); i++) ans += cnt[i]; } else { cnt[1] = (h[0] + b) / b; cnt[n - 2] = (h[n - 1] + b) / b; h[1] -= cnt[1] * a; h[2] -= cnt[1] * b; h[n - 2] -= cnt[n - 2] * a; h[n - 3] -= cnt[n - 2] * b; mem = cnt; ans = INF; mp.clear(); dfs(cnt[1] + cnt[n - 2]); } cout << ans << "\n"; for (int i = 1; i < (n); i++) while (cnt[i]) { cout << i + 1 << " "; cnt[i]--; } }
### Prompt Please create a solution in CPP to the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; const int INF = 0x3f3f3f3f; namespace fastIO { bool IOerror = 0; inline char nc() { static char buf[100000], *p1 = buf + 100000, *pend = buf + 100000; if (p1 == pend) { p1 = buf; pend = buf + fread(buf, 1, 100000, stdin); if (pend == p1) { IOerror = 1; return -1; } } return *p1++; } inline bool blank(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; } inline bool read(int &x) { char ch; bool ne = false; while (blank(ch = nc())) ; if (IOerror) return false; if (ch == '-') ne = true, ch = nc(); for (x = ch - '0'; (ch = nc()) >= '0' && ch <= '9'; x = x * 10 + ch - '0') ; if (ne) x = -x; return true; } inline bool read(long long &x) { char ch; bool ne = false; while (blank(ch = nc())) ; if (IOerror) return false; if (ch == '-') ne = true, ch = nc(); for (x = ch - '0'; (ch = nc()) >= '0' && ch <= '9'; x = x * 10 + ch - '0') ; if (ne) x = -x; return true; } }; // namespace fastIO using namespace fastIO; const int N = 30; int h[N]; vector<char> cnt; vector<char> mem; int n; inline int check() { int tmp = max_element(h + 1, h + n - 1) - h; if (h[tmp] >= 0) return tmp; else return -1; } int a, b, ans; set<vector<char>> mp; void dfs(int pos) { if (mp.count(mem)) return; mp.insert(mem); int tmp = check(); if (tmp == -1) { if (ans > pos) cnt = mem, ans = pos; return; } int tt = 0; for (int i = 1; i < (n - 1); i++) { if (h[i] < 0 && h[i - 1] < 0) continue; h[i] -= a; h[i - 1] -= b; h[i + 1] -= b; mem[i]++; dfs(pos + 1); h[i] += a; h[i - 1] += b; h[i + 1] += b; mem[i]--; if (tt++ > 1) break; } } int main() { read(n), read(a), read(b); for (int i = 0; i < (n); i++) read(h[i]), cnt.push_back(0); if (n == 3) { cnt[1] = max((h[0] + b) / b, (h[2] + b) / b); h[1] -= cnt[1] * a; if (h[1] >= 0) cnt[1] += (h[1] + a) / a; ans = 0; for (int i = 1; i < (n); i++) ans += cnt[i]; } else { cnt[1] = (h[0] + b) / b; cnt[n - 2] = (h[n - 1] + b) / b; h[1] -= cnt[1] * a; h[2] -= cnt[1] * b; h[n - 2] -= cnt[n - 2] * a; h[n - 3] -= cnt[n - 2] * b; mem = cnt; ans = INF; mp.clear(); dfs(cnt[1] + cnt[n - 2]); } cout << ans << "\n"; for (int i = 1; i < (n); i++) while (cnt[i]) { cout << i + 1 << " "; cnt[i]--; } } ```
#include <bits/stdc++.h> int n, a, b, h[10], tmp[200], res[200], num = 0, ans = 0, sum[16]; void desc(int x) { h[x] -= a; h[x + 1] -= b; h[x - 1] -= b; tmp[num++] = x; } void back(int newNum) { while (num > newNum) { int x = tmp[--num]; h[x] += a; h[x + 1] += b; h[x - 1] += b; } } void dfs(int x) { if (num + sum[x] / (a + b + b) > ans) { return; } int lastNum = num; if (x == n - 1) { while (h[x] >= 0) desc(x - 1); if (num < ans) { ans = num; memcpy(res, tmp, num * sizeof(int)); } return back(lastNum); } while (h[x - 1] >= 0) { desc(x); } dfs(x + 1); while (h[x] >= 0) { desc(x); dfs(x + 1); } return back(lastNum); } int main() { scanf("%d %d %d", &n, &a, &b); for (int i = 0; i < n; i++) scanf("%d", &h[i]); for (int i = n - 1; i >= 0; i--) { int k = (i > 0 && i < n - 1) ? a : b; ans += h[i] / k + 1; sum[i] = sum[i + 1] + h[i] + 1; } dfs(1); printf("%d\n", ans); for (int i = 0; i < ans; i++) printf("%d ", res[i] + 1); }
### Prompt Generate a CPP solution to the following problem: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> int n, a, b, h[10], tmp[200], res[200], num = 0, ans = 0, sum[16]; void desc(int x) { h[x] -= a; h[x + 1] -= b; h[x - 1] -= b; tmp[num++] = x; } void back(int newNum) { while (num > newNum) { int x = tmp[--num]; h[x] += a; h[x + 1] += b; h[x - 1] += b; } } void dfs(int x) { if (num + sum[x] / (a + b + b) > ans) { return; } int lastNum = num; if (x == n - 1) { while (h[x] >= 0) desc(x - 1); if (num < ans) { ans = num; memcpy(res, tmp, num * sizeof(int)); } return back(lastNum); } while (h[x - 1] >= 0) { desc(x); } dfs(x + 1); while (h[x] >= 0) { desc(x); dfs(x + 1); } return back(lastNum); } int main() { scanf("%d %d %d", &n, &a, &b); for (int i = 0; i < n; i++) scanf("%d", &h[i]); for (int i = n - 1; i >= 0; i--) { int k = (i > 0 && i < n - 1) ? a : b; ans += h[i] / k + 1; sum[i] = sum[i + 1] + h[i] + 1; } dfs(1); printf("%d\n", ans); for (int i = 0; i < ans; i++) printf("%d ", res[i] + 1); } ```
#include <bits/stdc++.h> using namespace std; const int maxn = (1e5) + 9; int h[20]; int an[160]; int n, a, b; bool dfs(int ans, int x, int l) { if (ans == 0) { for (int i = 1; i <= n; i++) { if (h[i] >= 0) return false; } return true; } if (h[x] < 0) return dfs(ans, x + 1, l); if (x == n) { h[n] -= b; an[ans] = n - 1; if (dfs(ans - 1, x, l)) return true; h[n] += b; } else { for (int i = max(x, l); i <= x + 1; i++) { if ((1 < i) && (i < n)) { an[ans] = i; h[i] -= a; h[i - 1] -= b; h[i + 1] -= b; if (dfs(ans - 1, x, i)) return true; h[i] += a; h[i - 1] += b; h[i + 1] += b; } } } return false; } int main() { scanf("%d%d%d", &n, &a, &b); int i, j; for (i = 1; i <= n; i++) { scanf("%d", h + i); } int ans = 1; while (true) { if (dfs(ans, 1, 2)) { printf("%d\n", ans); i = ans; while (i) { printf("%d ", an[i]); i--; } printf("\n"); return 0; } ans++; } return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = (1e5) + 9; int h[20]; int an[160]; int n, a, b; bool dfs(int ans, int x, int l) { if (ans == 0) { for (int i = 1; i <= n; i++) { if (h[i] >= 0) return false; } return true; } if (h[x] < 0) return dfs(ans, x + 1, l); if (x == n) { h[n] -= b; an[ans] = n - 1; if (dfs(ans - 1, x, l)) return true; h[n] += b; } else { for (int i = max(x, l); i <= x + 1; i++) { if ((1 < i) && (i < n)) { an[ans] = i; h[i] -= a; h[i - 1] -= b; h[i + 1] -= b; if (dfs(ans - 1, x, i)) return true; h[i] += a; h[i - 1] += b; h[i + 1] += b; } } } return false; } int main() { scanf("%d%d%d", &n, &a, &b); int i, j; for (i = 1; i <= n; i++) { scanf("%d", h + i); } int ans = 1; while (true) { if (dfs(ans, 1, 2)) { printf("%d\n", ans); i = ans; while (i) { printf("%d ", an[i]); i--; } printf("\n"); return 0; } ans++; } return 0; } ```
#include <bits/stdc++.h> using namespace std; int ans = 9999999; int h[100]; int a, b, n; vector<int> V; vector<int> V2; void dfs(int x, int times) { if (times >= ans) return; if (x == n) { if (h[x] < 0) { V2 = V; ans = times; } return; } for (int i = 0; i <= max(h[x - 1] / b + 1, max(h[x] / a + 1, h[x + 1] / b + 1)); i++) { if (h[x - 1] < b * i) { h[x - 1] -= b * i; h[x] -= a * i; h[x + 1] -= b * i; for (int j = 0; j < i; j++) V.push_back(x); dfs(x + 1, times + i); for (int j = 0; j < i; j++) V.pop_back(); h[x - 1] += b * i; h[x] += a * i; h[x + 1] += b * i; } } } int main() { cin >> n >> a >> b; for (int i = 1; i <= n; i++) cin >> h[i]; dfs(2, 0); cout << ans << endl; for (int i = 0; i < V2.size(); i++) cout << V2[i] << " "; cout << endl; return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int ans = 9999999; int h[100]; int a, b, n; vector<int> V; vector<int> V2; void dfs(int x, int times) { if (times >= ans) return; if (x == n) { if (h[x] < 0) { V2 = V; ans = times; } return; } for (int i = 0; i <= max(h[x - 1] / b + 1, max(h[x] / a + 1, h[x + 1] / b + 1)); i++) { if (h[x - 1] < b * i) { h[x - 1] -= b * i; h[x] -= a * i; h[x + 1] -= b * i; for (int j = 0; j < i; j++) V.push_back(x); dfs(x + 1, times + i); for (int j = 0; j < i; j++) V.pop_back(); h[x - 1] += b * i; h[x] += a * i; h[x + 1] += b * i; } } } int main() { cin >> n >> a >> b; for (int i = 1; i <= n; i++) cin >> h[i]; dfs(2, 0); cout << ans << endl; for (int i = 0; i < V2.size(); i++) cout << V2[i] << " "; cout << endl; return 0; } ```
#include <bits/stdc++.h> const int MAXN = 11; using namespace std; int hit[MAXN], n, a, b, h[MAXN], ans, fa[MAXN]; bool dfs(int l, int k, int last) { if (k == 0) { int flag = 0; for (int i = 1; i <= n; i++) if (h[i] >= 0) flag = 1; if (!flag) return 1; else return 0; } if (h[l] < 0) { return dfs(l + 1, k, last); } for (int i = min(n - 1, max(last, max(2, l))); i <= min(n - 1, l + 1); i++) { h[i] -= a; h[i - 1] -= b; h[i + 1] -= b; if (dfs(l, k - 1, i)) { fa[k] = i; return 1; } h[i] += a; h[i - 1] += b; h[i + 1] += b; } return 0; } int main() { scanf("%d %d %d", &n, &a, &b); for (int i = 1; i <= n; i++) scanf("%d", &h[i]); for (int i = 1;; i++) { memset(fa, 0, sizeof(fa)); if (dfs(1, i, 2)) { printf("%d\n", i); for (int j = 1; j <= i; j++) { printf("%d ", fa[j]); } return 0; } } }
### Prompt Please provide a Cpp coded solution to the problem described below: This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each. As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed. Input The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has. Output In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order. Examples Input 3 2 1 2 2 2 Output 3 2 2 2 Input 4 3 1 1 4 1 1 Output 4 2 2 3 3 ### Response ```cpp #include <bits/stdc++.h> const int MAXN = 11; using namespace std; int hit[MAXN], n, a, b, h[MAXN], ans, fa[MAXN]; bool dfs(int l, int k, int last) { if (k == 0) { int flag = 0; for (int i = 1; i <= n; i++) if (h[i] >= 0) flag = 1; if (!flag) return 1; else return 0; } if (h[l] < 0) { return dfs(l + 1, k, last); } for (int i = min(n - 1, max(last, max(2, l))); i <= min(n - 1, l + 1); i++) { h[i] -= a; h[i - 1] -= b; h[i + 1] -= b; if (dfs(l, k - 1, i)) { fa[k] = i; return 1; } h[i] += a; h[i - 1] += b; h[i + 1] += b; } return 0; } int main() { scanf("%d %d %d", &n, &a, &b); for (int i = 1; i <= n; i++) scanf("%d", &h[i]); for (int i = 1;; i++) { memset(fa, 0, sizeof(fa)); if (dfs(1, i, 2)) { printf("%d\n", i); for (int j = 1; j <= i; j++) { printf("%d ", fa[j]); } return 0; } } } ```