题目内容:
Input Specification:
Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.
Output Specification:
For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.
就我自己的理解而言,这道题是模拟数据的入栈和出栈,需要数据按顺序进行入栈,并在合适的时候出栈,才能够判断其到底能不能得到输入行的数据顺序。
我的题解:
main函数:
1 int main(){ //主函数 2 #ifdef ONLINE_JUDGE //如果有oj系统(在线判定),则忽略文件读入,否则使用文件作为标准输入 3 #else 4 freopen("1.txt", "r", stdin); //从1.txt输入数据 5 #endif 6 int m,n=0,k; 7 cin>>m>>n>>k; 8 int s[maxsize][maxsize];//在前面定义了maxsize=1000 9 10 //输入数据 11 for(int i=0;i<k;i++){ 12 for(int j=0;j<n;j++) 13 cin>>s[i][j]; 14 } 15 for(int i=0;i<k;i++){ 16 if(ispop(m,n,s[i])){//调用ispop函数 17 cout<<"YES"<<endl; 18 } 19 else cout<<"NO"<<endl; 20 } 21 //加入自己的代码 22 return 0; //返回0,如果不返回0,PAT会报错 23 }
ispop函数:
1 bool ispop(int m,int n,int a[]){ 2 int i=1; 3 int *b=new int[n]; 4 stack<int> s; 5 int j=0;//s.push(i); 6 while(i<=n){ 7 if(s.size()>m)return 0;//如果大于栈的最大容量m,则错误 8 if(i>a[j])//如果i比a[j]大则需要pop(一旦有比i小的元素,说明前面一定出栈了) 9 if(s.empty()){return 0;} 10 b[j]=s.top(); 11 s.pop(); 12 j++; 13 } 14 else 15 {s.push(i); 16 i++;} 17 } 18 if(s.size()>m)return 0; 19 while(!s.empty()){ 20 b[j]=s.top(); 21 s.pop(); 22 j++; 23 } 24 for(int x=0;x<n;x++){//判别pop出的数据是否和原数组一样 25 26 if(a[x]==b[x]); 27 else return 0; 28 } 29 return 1; 30 }
在网上查过各博主写的代码以后,思路是一样的,但是在判定出栈时,有一个细小的差别。其是当栈顶元素和数组元素相等时,进行pop操作
如下:
1 bool ispop(int m,int n,int a[]){ 2 3 int i=1; 4 //int *b=new int[n]; 5 stack<int> s; 6 int j=0;//s.push(i); 7 while(i<=n){ 8 if(s.size()>=m)return 0;//如果大于栈的最大容量m,则错误 9 s.push(i); 10 i++; 11 while(!s.empty()&&s.top()==a[j]){//这里的出栈的条件:变成了站顶元素是否与a[j]相等 12 //改成相等以后(每一次pop都是严格按照a中的顺序),便无需再构造一个数组来判定出栈元素与a中的元素是否相同了 13 //这里的两个条件不能互换位置 14 s.pop(); 15 j++; 16 } 17 } 18 if(j==n)return 1; 19 else return 0;
posted on
浙公网安备 33010602011771号