Answer the question
In order to leave comments, you need to log in
How to solve a vertex problem in C++ with minimal code?
Conditions of the problem:
There is a certain type of tax for travel agencies that organize routes through the mountains, its value depends only on the horizontal movement, and does not depend at all on the height of the mountains. At the input of the program are given: first, the number N, which means the number of heights of the vertices that will be entered, then the heights of the vertices themselves are entered. To save on tax, you need to make a minimum route, but since the route passes through the mountains, there must be an ascent and descent, that is, there must be a point that is strictly above the beginning and end of the route. The program should output two numbers, the number of vertices where the route was started and ended accordingly. If it was not possible to create a route that satisfies the condition, output 0. Example input: 7 18 10 15 20 20 10 3, corresponding output: 3 6. Explanation, the shortest route here would be 15 20 20 10, 15 is number 3 and 10 is number 6. Second example. Input: 3 9 8 5 Output: 0
Answer the question
In order to leave comments, you need to log in
std::vector<int> heights{18, 10, 15, 20, 20, 10, 3} ;
size_t bestLen = 0;
size_t bestIndex = 0;
// путь не может быть проложен из последних двух вершин
for(size_t i = 0; i < heights.size() - 2; ++i)
{
// начало пути должно быть в гору
if(heights[i + 1] <= heights[i])continue;
// прокладываем путь до ближайшего спуска
for(size_t j = i + 2; j < heights.size(); ++j)
{
if(heights[j] > heights[j-1])break; // подъём встретился до спуска, решение заведомо неоптимально
if(heights[j] < heights[j-1])
{
size_t len = j - i;
if(len < bestLen || bestLen == 0)
{
bestLen = len;
bestIndex = i;
}
break;
}
}
}
if(bestLen == 0)
{
std::cout << 0 << std::endl;
}
else
{
std::cout << bestIndex + 1 << " " << bestIndex + bestLen + 1 << std::endl;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question