c++栈的练习题

1. Problem Detail - 【入门】火车编组 - 追梦算法网

栈的练习题

#include<stdio.h>
#include<stack>
#include <vector>
#include<iostream>
#include<string.h>
using namespace std;
const int N = 100;
int main()
{
stack<int>nums;
int code[100];
int n,num,t = 1;
cin>>n;
for(int i = 1; i <= n;i++){
	cin>>code[i];	
	nums.push(i);
	cout<<"A";
	while(!nums.empty()&&nums.top() == code[t]&&t <= i){
		cout<<"B";
		nums.pop();
		t++;
	}
}
	while(!nums.empty()){
		nums.pop();
		cout<<"B";
	}
	return 0;
 } 

 2.Problem Detail - 离间计 - 追梦算法网

虽然在栈的分类里面,但最后还是用了数组

#include <bits/stdc++.h>
using namespace std;
const int N=1e5+7;
int w[N];
int main(){
	int t,n;
	cin>>t;
	while(t--){
		cin>>n;
		for(int i=0;i<n;i++){
			scanf("%d",&w[i]);
		}
		for(int i=0;i<n;i++){
			int flag=0;
			for(int j=i-1;j>=0;j--){
				if(w[j]<w[i]&&i!=n-1){
					flag=1;
					cout<<j<<" ";
					break;
				}
				else if(w[j]<w[i]&&i==n-1){
					flag=1;
					cout<<j;
					break;
				}
			}
			if(flag==0&&i!=n-1) cout<<-1<<" ";
			else if(flag==0&&i==n-1) cout<<-1;
		}
		cout<<endl; 
	}
	return 0;

3.Problem Detail - QAQ和车库 - 追梦算法网

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+7;
int SS[N],top=-1;
int n,k,v,maxx=0;
int main() {
	scanf("%d",&n);
	while(n--){
		scanf("%d",&k);
		if(k==1){
			scanf("%d",&v);
			if(v>maxx)SS[++top]=v,maxx=v;
			else SS[++top]=maxx;
		}else if(k==2){
			maxx=SS[--top];
		}else{
			if(top==-1) printf("%d\n",-1);
			else printf("%d\n",SS[top]);
		}
	}
	return 0;
}

4.Problem Detail - A Famous City - 追梦算法网

#include<iostream>
#include<stack>
using namespace std;
/*
判定为相同的建筑的情况
1.两个建筑高度相同
2.两个建筑之间没有更低的建筑 
*/ 
stack<int> build;
int main()
{
	ios::sync_with_stdio(false);
	int n,k,x;
	cin>>n;
	for(int j = 1; j <= n; j++){
		int ans = 0l;
		cin>>k;
		for(int i = 0; i < k; i++){
     //通过让建筑保持单调递增的情况,从而使每清除一个建筑就代表数量加一
     cin>>x;
          while(!build.empty()&&build.top()>x){
	      ans++;
	      build.pop();
} 
if(x == 0)continue;
if(build.empty()||build.top() < x){
	build.push(x);
}
		} 
			while(!build.empty()){
		ans++;
		build.pop();
	}
	cout<<"Case "<<j<<": "<<ans<<endl;
	}

	return 0;
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值