标签:
题目链接: http://poj.org/problem?id=1028
题意: 模拟浏览器的前进/后退/访问/退出 的四个操作. 输出当前访问的URL或者Ignore(如果不能前进/后退).
分析: 用一个vector加上当前位置索引index即可. 当进行visit一个新的URL时, 应该基于当前URL重新建立FORWORD表(清空以前的FORWORD元素即可).
教训: 操作容器时, 如果对容器进行改变, 那么对应的size()等等也要考虑变化, 否则机会出错.
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 vector<string> vs; 5 int main(){ 6 string cmd; 7 string addr; 8 int index = 0; 9 vs.push_back(string("http://www.acm.org/")); 10 while(cin>>cmd && cmd != "QUIT"){ 11 if(cmd == "VISIT"){ 12 cin>>addr; 13 /* 这样会wa,因为pop_back()操作会影响到for循环中的条件vs.size()的改变. 14 if(index != vs.size()-1){ 15 for(int i=0;i<vs.size()-index-1;++i){ 16 vs.pop_back(); 17 } 18 } 19 */ 20 while(index < vs.size()-1){ 21 vs.pop_back(); 22 } 23 vs.push_back(addr); 24 index++; 25 cout<<vs[index]<<endl; 26 }else if(cmd == "BACK"){ 27 if(index==0){ 28 cout<<"Ignored"<<endl; 29 }else{ 30 index--; 31 cout<<vs[index]<<endl; 32 } 33 }else if(cmd == "FORWARD"){ 34 if(index==vs.size()-1){ 35 cout<<"Ignored"<<endl; 36 }else{ 37 index++; 38 cout<<vs[index]<<endl; 39 } 40 }else{ 41 cout<<"Ignored"<<endl; 42 } 43 } 44 return 0; 45 }
标签:
原文地址:http://www.cnblogs.com/roger9567/p/4887093.html