Quick overview of the minimum tile path problem and detailed code explanation (greedy algorithm)

1. Problem description

 

2. Scene construction

Xiao Liu, the contractor, was going to pave the road . The construction site gave a series of bricks . These bricks were of different lengths. The road was fixed, and the bricks would definitely be able to pave the road. The position where each brick could be placed was also fixed. The bricks paved the road.

 

3. Greedy strategy selection

Now assume that the bricks given by the construction site have been arranged from left to right according to the starting position of the bricks (the value of the number axis is from low to high), and the length of the bricks is also arranged from low to high (that is, l1 <= l2 <= ... < in X = ln, when li = li+1, ui <= ui+1)

Xiao Liu decided to use this method to pave the way:

The brick selected each time is guaranteed to be connected to the previous brick

Prioritize more bricks that can pave the way forward

 

4. Detailed explanation of code and comments

An example is given here as X[7][2] = { {1,2},{1,6},{2,7},{4,8},{7,9},{8, 10},{9,10}}

The output result is shown in the figure below:

Print the bricks selected by the minimum tile path, the length of the minimum tile path, respectively

Below is the code and comments

#include <cstdlib>
#include <cstdio>
#include <iostream>

using namespace std;

// 贪心策略:
// 每次选择的砖块,在保证能和前一块砖块连接的基础上
// 尽量选择往前铺的路更多的

int Min_road(double X[][2], int size){
    int new_road = 0;                           // 最新的被选进最小平铺路径的砖块下标
    double cover_end = X[0][0];                 // 目前路径铺到哪里了(工程进度)
    int search = 0;                             // 找到第几块地砖了(目前遍历到的地砖下标)
    int count = 0;                              // 目前最小平铺路径中的地砖数量
    int X_length = size;
    

    // 遍历地砖,寻找最小平铺路径的地砖
    while(search < X_length){

        double blank_coverage = 0;              // 选择的地砖能再往前铺多少长度的路
        int bc_record = new_road;               // 选择的地砖的下标

        for(; search<X_length && X[search][0]<=cover_end; search++){    // 找的地砖开始不能和前一块脱节,就退出本次查找
            if(X[search][1]-X[new_road][1]>=blank_coverage){            // 如果当前地砖铺的路更多
                blank_coverage = X[search][1]-X[new_road][1];           // 记录这块地砖以及它铺的路的长度
                bc_record = search;
            }
        }

        new_road = bc_record;                   // 将地砖纳入最小平铺路径
        cover_end = X[new_road][1];             // 更新工程进度
        count++;                                // 更新砖块数量

        cout << "[" << X[new_road][0] << ", " << X[new_road][1] << "]  "; 

        if (X[new_road][1] == X[size-1][1])     // 路铺完了,立即结束工程
            break;
    }

    return count;
}

int main(){
    double X[7][2] = {
   
   {1,2},{1,6},{2,7},{4,8},{7,9},{8,10},{9,10}};
    int count = Min_road(X, 7);
    cout << '\n' << "长度为:" << count;
}

 

Guess you like

Origin blog.csdn.net/m0_56942491/article/details/124255485