gpt4 book ai didi

c++ - 找到小于或等于当前塔的先前塔的数量

转载 作者:行者123 更新时间:2023-11-28 04:57:15 24 4
gpt4 key购买 nike

您好,我正在尝试查找小于或等于当前塔的先前塔的数量,此解决方案对输入(NumOfTowers)<=10 非常有效,但对于 NumOfTowers >10,代码将出现段错误,我在这里看不到问题,

#include <iostream>
#include <stack>
using namespace std;

int main()
{
std::stack<int> Towers; //for storing the Height of the towers
std::stack<int> TempTowers; // Temrory buffer stack
std::stack<int> CountTowers; //for storing the count of all previous
towers less than the current one
unsigned int NumTestCases,NumOfTowers,i,j,count=1,temp,temp_height;
cin>>NumTestCases;
cin>>NumOfTowers;


while(NumTestCases){

while(!Towers.empty()){
Towers.pop();
}
for(i=0;i<NumOfTowers;i++){
cin>>temp;
Towers.push(temp);
}
for(i=0;i<NumOfTowers-1;i++){
count=1;
temp_height=Towers.top();
Towers.pop();
temp=Towers.top();

while(temp<temp_height){
count++;
TempTowers.push(temp);
Towers.pop();
temp=Towers.top();
}

CountTowers.push(count);

while(!TempTowers.empty()){
temp=TempTowers.top();
TempTowers.pop();
Towers.push(temp);
}

}
NumTestCases--;
cout<<"1"<<" ";
while(!CountTowers.empty()){
cout<<CountTowers.top()<<" ";
CountTowers.pop();
}
cout<<"\n";
}

}

任何帮助都会很棒。

最佳答案

改变这个

while(temp<temp_height){
count++;
TempTowers.push(temp);
Towers.pop(); // Popped the last element
temp=Towers.top(); // no more elements left
}

对此

while(!Towers.empty() && Towers.top() < temp_height)
{
++count;
TempTowers.push(Towers.top());
Towers.pop();
}

问题不在于输入的长度,而在于输入的顺序。如果 I/p = {1, 2, 3, 4} 您的代码在尝试访问空堆栈的 top() 时会出错。

关于c++ - 找到小于或等于当前塔的先前塔的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46883974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com