HackerRank--Equal Stacks

HackerRank–Equal Stacks

题目描述

有三个栈,每个栈里放了一些高度不一的圆柱体,问如何从最上面拿走任意数量的圆柱体使三个栈的高度一致,最大可以得到的高度是多少?
// 因为栈为空也视为高度一致,所以一定有解。

分析

只需要计算出每一个圆柱体处的当前总高度,即求一个前缀和代替之前的单独的高度值。
每次比较两个栈,把较高的顶部的圆柱体拿掉(退栈),直到使两个栈等高,重复该操作使 height_1 = height_2= height_3 即可。

然后要注意题目里给的圆柱体高度是从上到下的,输入的时候需要反过来。

实现

#include <queue>
#include <vector>
#include <iostream>

using namespace std;

int equalize_stack(vector<int>& a, vector<int>& b) {
    if (a.empty()) {
        while (!b.empty()) b.pop_back();
        return 0;
    }
    if (b.empty()) {
        while (!a.empty()) a.pop_back();
        return 0;
    }
    while (!a.empty() || !b.empty()) {
        int al = a.empty() ? 0 : a[a.size()-1];
        int bl = b.empty() ? 0 : b[b.size()-1];
        if (al > bl) {
            a.pop_back();
        } else if (al < bl) {
            b.pop_back();
        } else {
            return al;
        }
    }
    return 0;
}

int main(){
    int n1;
    int n2;
    int n3;
    cin >> n1 >> n2 >> n3;
    vector<int> h1(n1);
    for(int h1_i = n1-1; h1_i >= 0; h1_i--){
       cin >> h1[h1_i];
    }
    for (int i = 0; i < n1; i++) {
        h1[i] += i ? h1[i - 1] : 0;
        // cout << h1[i] << ' ';
    }

    vector<int> h2(n2);
    for(int h2_i = n2-1; h2_i >= 0; h2_i--){
       cin >> h2[h2_i];
    }
    for (int i = 0; i < n2; ++i) {
        h2[i] += i ? h2[i - 1] : 0;
        // cout << h2[i] << ' ';
    }

    vector<int> h3(n3);
    for(int h3_i = n3-1;h3_i >= 0; h3_i--){
       cin >> h3[h3_i];
    }
    for (int i = 0; i < n3; ++i) {
        h3[i] += i ? h3[i - 1] : 0;
        // cout << h3[i] << ' ';
    }

    int al = equalize_stack(h1, h2);
    int bl = equalize_stack(h2, h3);
    while (al != bl) {
        al = equalize_stack(h1, h2);
        bl = equalize_stack(h2, h3);
    }
    cout << al << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/cyz14/article/details/70050361