塔由桶 - 加速alghoritm

时间:2018-04-26 21:51:02

标签: c++ algorithm data-structures stack

我需要加快算法速度。这是关于找到塔的高度。塔是用水桶建造的。每个铲斗具有高度和半径(1 <=高度,半径<= 1000)。变量this.toggleCanvasMarkersVisibility(true); // This code sets visibility to visible // Create a snapshot of the map as follows: this.map.getCanvas().toBlob(function (blob) { canvasContext.strokeStyle = '#CCCCCC'; canvasContext.strokeRect(leftPosition, topPosition, width, height); var img = new Image(); img.setAttribute("crossOrigin", "anonymous"); var srcURL = URL.createObjectURL(blob); img.onload = function () { canvasContext.drawImage(img, leftPosition, topPosition, width, height); // Other operations }); 描述了在塔上放置了多少桶(1&lt; = bucketCount&lt; = 10 6 )。我们按顺序设置存储桶。桶的厚度为0(为简单起见)

示例塔的图像

Image of example tower

我决定使用堆栈。我的每个桶的算法:

  1. 如果堆栈为空,则将桶推入堆栈,
  2. 如果我拿着的水桶较窄,则将水桶放在上面,然后将其放在烟囱上
  3. 另外我拿着的水桶更宽:弹出并找到最大高度(对于新的水桶地面),在我持有的推水桶之后。
  4. 对于每个水桶,我添加了额外的可变地面,用于指定放置哪个高度水桶。同时我保持塔的最大高度变化。

    我想这虽然需要花费太多时间,但我无法想办法欺骗它。有没有办法加快?我使用了分析,我知道bucketCount需要花费很多时间。

    示例输入:top()
    输出:50

    2 20 20 30 30

    更新#1

    #include <iostream>
    #include <stack>
    
    using namespace std;
    
    class Bucket{
    public:
        int height;
        int radius;
        int ground;
    };
    
    int main()
    {
        stack<Bucket> tower;
        int hightestPoint = 0;
        int bucketCount;
        cin >> bucketCount;
        Bucket temp;
        int maksimum;
        int sum;
        for(int i = 0; i < bucketCount; i++){
            cin >> temp.radius >> temp.height;
            maksimum = -1;
            sum = 0;
            if(tower.empty()){
                temp.ground = 0;
                tower.push(temp);
            } else {
                if(temp.radius < tower.top().radius){ //If bucket is narrower then push it
                    temp.ground = tower.top().ground;
                    tower.push(temp);
                } else { //If bucket is wider
                    while(!tower.empty() && temp.radius >= tower.top().radius){ //Pop and search for new ground (maximum)
                        sum = tower.top().height + tower.top().ground;
                        if(maksimum < sum){
                            maksimum = sum;
                        }
                        tower.pop();
                    }
                    temp.ground = maksimum; //Set ground for new bucket
                    tower.push(temp);
                }
            }
            sum = tower.top().height + tower.top().ground; //Meantime find highest point in stack
            if(hightestPoint < sum){
                hightestPoint = sum;
            }
        }
        cout << hightestPoint << endl;
    
        return 0;
    }
    

1 个答案:

答案 0 :(得分:0)

编辑:正如马特指出的那样,不需要编辑。

while语句循环遍历堆栈,发现存储桶比新存储区宽。这基本上是在列表中找到一个元素,只比一些新元素小。使用二进制搜索或将列表存储在集合中可以轻松完成。

要实现此功能,您可以使用vector来维护堆栈,然后使用lower_bound查找相应的存储分区。