繁体   English   中英

查找以前的塔数少于或等于当前的塔数

[英]find the number of previous towers less than or equal to the current one

嗨,我正在尝试查找小于或等于当前塔数的先前塔数,此解决方案对于输入(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";
    }

}

任何帮助都会很棒。

改变这个

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()时,您的代码将给出错误。

您正在调用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM