Question Details

No question body available.

Tags

c++ algorithm lexicographic

Answers (2)

Accepted Answer Available
Accepted Answer
September 2, 2025 Score: 11 Rep: 91,758 Quality: Expert Completeness: 60%

It is possible to use string hashing and binary lifting to speed up your current solution, but there is a simpler method.

The minimal string can be built one character at a time, starting from the character at the top left corner.

To get each subsequent character, check the characters to the right and bottom of each of the possible positions of the previous character and eliminate duplicate positions. Then, take the minimum of the characters at all these positions and discard the positions that are not equal to that character for the next iteration.

#include 
#include 
#include 
#include 
#include 
#include 

int main() { int n; std::cin >> n; std::vector grid(n); for (auto& row : grid) std::cin >> row; std::vector positions{{0, 0}}; while (!positions.empty()) { positions.erase(std::ranges::unique(positions).begin(), positions.end()); char minc = std::ranges::min(positions | std::views::transform([&](auto& p) { return grid[p.first][p.second]; })); std::cout
September 2, 2025 Score: 0 Rep: 21,196 Quality: Low Completeness: 20%

Construct a graph whose nodes are the grid cells. Eah cell node ( except the bottom and RHS calls ) has edges to the the cell on the right, below and diagonally below and right. The cost of traversing each edge is the increment between the letters in the cells ( e.g. A->B is 1, but B->A is -1).

Find the edge with the most -ve cost. Add the absolute value of that cost to the cost of every edge ( so that every edge has a zero or +ve cost).

Apply the Dijkstra algorithm to find the cheapest path from start to finish.