1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <stdlib.h> 5 #include <bits/stdc++.h> 6 using namespace std; 7 8 int main() 9 { 10 string str; 11 12 stack<int> s; 13 vector<vector<int> > vec; 14 int flag=1; 15 16 cin>>str; 17 for(int i=0;i<str.length();i++) 18 { 19 if(str[i]==‘(‘) 20 { 21 //下标入栈 22 s.push(i+1); 23 } 24 else if(str[i]==‘)‘) 25 { 26 if(s.empty()) 27 { 28 flag=0; 29 break; 30 } 31 else 32 { 33 int left=s.top(); 34 int right=i+1; 35 s.pop(); 36 vector<int> v; 37 v.push_back(left); 38 v.push_back(right); 39 vec.push_back(v); 40 } 41 } 42 } 43 if(flag&&s.empty()) 44 { 45 cout<<"Yes"<<endl; 46 for(int i=0;i<vec.size();i++) 47 { 48 cout<<vec[i][0]<<" "<<vec[i][1]<<endl; 49 } 50 } 51 else 52 { 53 cout<<"No"<<endl; 54 } 55 return 0; 56 }
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <stdlib.h> 5 #include <bits/stdc++.h> 6 using namespace std; 7 8 int main() 9 { 10 //提高输入输出的速度 11 ios::sync_with_stdio(false); 12 13 vector<string> vec; 14 int n; 15 cin>>n; 16 17 string do_what; 18 string url; 19 int cursor=0; 20 for(int i=0;i<n;i++) 21 { 22 cin>>do_what; 23 if(do_what=="VISIT") 24 { 25 while(!vec.empty()&&cursor<vec.size()-1) 26 { 27 vec.pop_back(); 28 } 29 cin>>url; 30 vec.push_back(url); 31 cout<<url<<endl; 32 cursor=vec.size()-1; 33 continue; 34 } 35 else if(do_what=="BACK") 36 { 37 cursor--; 38 if(!vec.empty()&&0<=cursor&&cursor<vec.size()) 39 { 40 cout<<vec[cursor]<<endl; 41 } 42 else 43 { 44 cout<<"Ignore"<<endl; 45 if(cursor<0) 46 { 47 cursor=0; 48 } 49 } 50 } 51 else if(do_what=="FORWARD") 52 { 53 cursor++; 54 if(!vec.empty()&&0<=cursor&&cursor<vec.size()) 55 { 56 cout<<vec[cursor]<<endl; 57 } 58 else 59 { 60 cout<<"Ignore"<<endl; 61 if(cursor==vec.size()) 62 { 63 cursor=vec.size()-1; 64 } 65 } 66 } 67 } 68 return 0; 69 }
也可以采用设置一个前进栈,一个后退栈的做法。
时间: 2024-12-30 01:20:42