您好我试图找到小于或等于当前塔的数量,此解决方案适用于输入(NumOfTowers)< = 10,但对于NumOfTowers> 10代码进入segfault,我在这里看不到问题,
#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";
}
}
任何帮助都会很棒。
答案 0 :(得分:1)
更改此
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()
时会出错。
答案 1 :(得分:0)
您正在空堆栈上调用temp=Towers.top();
,此处
while(temp<temp_height){
count++;
TempTowers.push(temp);
Towers.pop();
temp=Towers.top();
}
将此行更改为以下两行:
if (Towers.size() > 0) temp = Towers.top();
else break;