ZOJ 1061 Web Navigation

时间:2023-03-09 17:47:46
ZOJ 1061 Web Navigation

原题链接

题目大意:模拟一个浏览器,打开一个网页、后退或者前进,输出网址。

解法:用两个堆栈分别表示后退保存的网页和前进保存的网页。初始化时把当前页面压入后退堆栈的栈顶。要注意几点,一个是每次记得要清空两个堆栈,另一个,如果后退之后又打开了新的网页,前进的堆栈要清空,这和真实的浏览器的结果是一致的。

参考代码:

#include<iostream>
#include<string>
#include<stack> using namespace std; stack<string> back;
stack<string> forw; int main(){
int n;
cin>>n;
while(n--){
string cmd,url="http://www.acm.org/";
while(!back.empty())
back.pop();
while(!forw.empty())
forw.pop();
back.push(url); while(1){
cin>>cmd;
if(cmd=="QUIT")break;
if(cmd=="VISIT"){
cin>>url;
back.push(url);
cout<<url<<endl;
while(!forw.empty()) //visit new website, empty the forward stack
forw.pop();
}
if(cmd=="BACK"){
if(back.size()==1) //top url is the current
cout<<"Ignored"<<endl;
else{
forw.push(url);
back.pop();
url=back.top();
cout<<url<<endl;
}
}
if(cmd=="FORWARD"){
if(forw.empty())
cout<<"Ignored"<<endl;
else{
url=forw.top();
forw.pop();
back.push(url);
cout<<url<<endl;
}
}
}
if(n>0)
cout<<endl; } return 0;
}