solve this problem in c++
MAZE 2024 (Tên file MAZE2024.cpp)
An đã tạo ra một trò chơi mê cung và thách đố Bình.
Màn hình trò chơi được biểu diễn dưới dạng bảng gồm N dòng N cột. Mỗi ô tương ứng một trong các số từ 0 đến 9. Việc di chuyển đến một trong các ô này sẽ tốn một chi phí tương ứng với chữ số trong ô.
Yêu cầu: Biết rằng trò chơi điều khiển một robot di chuyển từ một ô ở cột 1 đến một ô ở cột N, hãy cho biết:
• Số lượng ô chữ số khác nhau ít nhất mà đường đi có thể đi qua
• Chi phí ít nhất khi di chuyển trên đường đi có số lượng ô chữ số khác nhau ít nhất.
Dữ liệu: Cho trong file văn bản MAZE2024.INP:
• Dòng đầu tiên gồm nguyên N (2 ≤ N ≤ 100) số dòng, số cột màn hình trò chơi.
• Dòng tiếp theo gồm 10 số nguyên v0, v1,..., v9 là chi phí khi đi vào ô có chữ số i
(1 ≤ vi ≤ 100)
• N dòng tiếp theo, mỗi dòng gồm một chuỗi N kí tự liên tiếp biểu diễn mê cung.
Kết quả: Ghi ra file văn bản MAZE2024.OUT gồm 2 dòng:
• Dòng đầu là số lượng ô chữ số khác nhau ít nhất
• Dòng thứ hai là chi phí ít nhất của đường đi có số lượng ô chữ số khác nhau ít nhất
Ví dụ:
MAZE2024.INP MAZE2024.OUT GIẢI THÍCH
6
8 1 2 1 9 14 8 8 6 9
287566
123444
983070
071311
548739
353665
3
9 Đường đi (tô màu đỏ) có số lượng chữ số khác biệt là 3, chi phí ít nhất là 9.
287566
123444
983070
071311
548739
353665
Assistant
To solve the MAZE2024 problem, we need to navigate through an N x N grid where each cell contains a digit from 0 to 9. Each digit represents a cost, and the objective is to find the path from any cell in the first column to any cell in the last column that uses the minimum number of distinct digits. Among paths with the same number of distinct digits, we also want to minimize the total cost.
Here's a comprehensive breakdown of the solution approach and the corresponding C++ implementation:
Solution Approach:
Input Parsing:
Read the grid size N.
Read the cost for digits v0 to v9.
Read the grid, where each cell contains a digit from 0 to 9.
State Representation:
State: Each state in our search is represented by the number of distinct digits used (num_digits_used), the current cost (cost), the current position (x, y), and the set of digits used so far (digit_set).
Priority Queue: We use a priority queue to explore states in the order of increasing num_digits_used and then by increasing cost.
Dijkstra's Algorithm:
Initialize the priority queue with all cells in the first column, since these are our starting points.
For each state, explore all possible moves (up, down, left, right) and update the priority queue with new states if they offer a better path in terms of num_digits_used and cost.
If a state reaches any cell in the last column, update the minimum number of distinct digits and the associated cost.
Optimizations:
Bitmasking: To efficiently track the set of digits used, we use a bitmask where each bit represents whether a digit has been encountered.
Early Termination: Since the priority queue is sorted by num_digits_used and cost, we can terminate the search as soon as we find the first valid path that reaches the last column.
Output:
After processing, output the minimum number of distinct digits and the corresponding minimum cost.
C++ Implementation:
cpp
#include <bits/stdc++.h>
using namespace std;
struct State {
int num_digits_used;
int cost;
int x, y;
int digit_set;
bool operator<(const State& other) const {
if(num_digits_used != other.num_digits_used)
return num_digits_used > other.num_digits_used; // min-heap based on num_digits_used
return cost > other.cost; // min-heap based on cost
}
};
const int INF = 1e9;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N;
cin >> N;
int v[10];
for(int i=0;i<10;i++) cin >> v[i];
vector<string> grid_str(N);
for(int i=0;i<N;i++) cin >> grid_str[i];
// Convert grid to digits
vector<vector<int>> grid(N, vector<int>(N, 0));
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++) {
grid[i][j] = grid_str[i][j] - '0';
}
}
// Initialize min_cost_arr
// Using a 1D array: x * N * 1024 + y * 1024 + mask
// Total size: N * N * 1024 <= 100 * 100 * 1024 = 10,240,000
// Allocate dynamically
// Initialize with INF
// To save memory, use a vector of unsigned int
// To make access faster, use a separate array
// But C++ doesn't support 10,240,000 size easily, use a vector
// Initialize with INF
// To save initialization time, use a vector of vectors
// Each cell has a vector of size 1024
// Initialize as:
// min_cost[x][y][mask]
// But to make it faster, flatten it
// Access as x * N * 1024 + y * 1024 + mask
// Precompute N * 1024
long long offset1 = N * 1024;
long long offset2 = 1024;
vector<int> min_cost_arr((long long)N * N * 1024, INF);
// Initialize the priority queue
priority_queue<State> pq;
for(int x=0; x<N; x++){
int y=0;
int digit = grid[x][y];
int mask = 1 << digit;
int num_digits = 1;
int cost = v[digit];
long long pos = (long long)x * offset1 + y * offset2 + mask;
if(cost < min_cost_arr[pos]){
min_cost_arr[pos] = cost;
pq.push(State{num_digits, cost, x, y, mask});
}
}
// Directions: up, down, left, right
int dx[4] = {-1, 1, 0, 0};
int dy_dir[4] = {0, 0, -1, 1};
// Initialize min_num_digits and min_cost
int min_num_digits = INF;
int min_cost = INF;
while(!pq.empty()){
State current = pq.top();
pq.pop();
// If current.num_digits_used > min_num_digits, we can stop
if(current.num_digits_used > min_num_digits){
break;
}
// If current is in last column
if(current.y == N-1){
if(current.num_digits_used < min_num_digits){
min_num_digits = current.num_digits_used;
min_cost = current.cost;
}
else if(current.num_digits_used == min_num_digits && current.cost < min_cost){
min_cost = current.cost;
}
// Since the queue is sorted, the first popped state in last column has the minimal D and minimal C
break;
}
// Explore neighbors
for(int dir=0; dir<4; dir++){
int nx = current.x + dx[dir];
int ny = current.y + dy_dir[dir];
if(nx < 0 || nx >= N || ny < 0 || ny >= N) continue;
int next_digit = grid[nx][ny];
int new_mask = current.digit_set | (1 << next_digit);
int new_num_digits = __builtin_popcount(new_mask);
int new_cost = current.cost + v[next_digit];
long long pos = (long long)nx * offset1 + ny * offset2 + new_mask;
if(new_cost < min_cost_arr[pos]){
min_cost_arr[pos] = new_cost;
pq.push(State{new_num_digits, new_cost, nx, ny, new_mask});
}
}
}
// After the loop, min_num_digits and min_cost should be set
cout << min_num_digits << "\n" << min_cost;
}
Explanation of the Code:
Reading Input:
The grid size N and the costs for each digit are read first.
The grid is then read as N strings, each containing N characters, which are converted to integers.
Initialization:
A 1D array min_cost_arr is used to keep track of the minimum cost for each cell and each possible digit set.
The priority queue pq is initialized with all cells in the first column. Each state includes the number of distinct digits used, the total cost, the current position, and the digit set.
Processing States:
The algorithm processes states from the priority queue, always choosing the state with the smallest number of distinct digits and then the smallest cost.
For each state, it explores all four possible directions (up, down, left, right).
If moving to a new cell results in a better cost, the state is updated and pushed back into the queue.
Termination:
The search terminates as soon as a state reaches the last column, ensuring that the path found has the minimum number of distinct digits and the minimum possible cost.
Output:
Finally, the minimum number of distinct digits and the corresponding minimum cost are printed.