從零起步看算法(第十九天 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;
}