基础数据结构(4)栈

从零起步看算法(第十九天 5.6)

//stack

1.栈的基础操作

 

#include <iostream>
#include<stack>
using namespace std;
stack<int>  S;
int main() {
    S.push(1);
    S.push(10);
    S.push(7);
    while(!S.empty()){
        cout<<S.top()<<endl;
        S.pop();
    }
    return 0;
}

2.两个经典的应用

1.火车入站和出站的顺序是否合法

2.括号匹配问题

3.括号匹配

真的是要吐了,卡了两天。

思路很简单就是,遇‘(’入栈,遇‘)’出栈。

格式,格式,格式!!!!!

一次输出两个的 格式,可以用ans[][2],二维数组来解决。

最后发现,编译器奇妙的不输出了,吐血,调了半天!!!

 

 

还有一个小的疑问,栈一定要在主函数外吗?

 

 

//括号匹配

//卡了两天的输出形式
 
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std; 

int ans[50000+5][2];


stack<int > q;//必须在主函数外吗
 


int main(){
	int c1=0;
	char ch;
	int cnt=0;
	
	while(scanf("%c",&ch)==1&&ch!=10){
		cnt++;
		if(ch=='(')
		q.push(cnt);
		
		if(ch==')'){
			if(q.empty()){
				cout<<"No"<<endl;
				return 0;
			}
			ans[c1][0]=q.top();
			ans[c1][1]=cnt;
			c1++;
			q.pop();
		}
	}
	if(!q.empty()){
		cout<<"No"<<endl;
		return 0;
	}
	else {
		cout<<"Yes"<<endl;
		for(int i=0;i<c1;i++){
			cout<<ans[i][0]<<" "<<ans[i][1];
			//if(i!=c1-1)
			cout<<endl;
	}	
  }
 
return 0;
}

4.网页跳转

提示:

慎用 C++ 的cin和cout,有可能会导致超时。

你可以在main函数的一开始加上ios::sync_with_stdio(false);

以提高输入输出的速度。

ios::sync_with_stdio(false)  使流的输入输出速度与C的输入输出持平
iostream默认是与stdio关联在一起的,以使两者同步,因此消耗了iostream不少性能,设置为false后,不再同步了,iostream的性能提高了很多倍。
而cin,cout之所以效率低,是因为先把要输出的东西存入缓冲区,再输出,导致效率降低,而这段语句可以来打消iostream的输入输出缓存,
可以节省许多时间,使效率与scanf与printf相差无几,还有应注意的是scanf与printf使用的头文件应是stdio.h而不是iostream。

本题要注意的也就是,细节把握,时刻保持逻辑清晰。

//网页跳转

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

stack<string> dict;
stack<string> res;

int main(){
	ios::sync_with_stdio(false);
	int n;
	cin>>n;
	while(n){
		string dir;  //指令
		cin>>dir;
		
		if(dir=="VISIT"){
			string str;
			cin>>str;
			
			while(!res.empty()){//清空 
				res.pop();
			}
			
			dict.push(str);
			cout<<dict.top()<<endl;
		} 
		
		if(dir=="BACK"){
			if(dict.empty()){
				cout<<"Ignore"<<endl;
				}
		    else{
		    	
		    	res.push( dict.top() );
				dict.pop();
				
				if(!dict.empty())
				cout<<dict.top()<<endl;
				
				else
				{ 
				cout<<"Ignore"<<endl;
				
				dict.push(res.top());//后退不了,即无操作 
				res.pop(); 
				}
				 
			}
		}
		
		if(dir=="FORWARD"){
			
			if(res.empty()){
				cout<<"Ignore"<<endl;
			}
			else{
				if(res.empty())
				cout<<"Ignore"<<endl;
				
				
				
				else{
					cout<<res.top()<<endl;
				    dict.push(res.top());
				    res.pop();
			
			     }
			}
		}
		n--;
	} 
	
	return 0;
} 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值