Web导航

【问题描述】

标准的Web浏览器具有在最近访问的页面中前后移动的特性。实现这些特性的一种方法是使用两个堆栈来跟踪可以通过前后移动到达的页面。在这个问题中,我们要求实现这一点。

   需要支持以下命令:

   BACK:将当前页面压入前向堆栈的顶部;从后向堆栈的顶部弹出该页,使其成为新的当前页。如果后向堆栈为空,则该指令忽略。

   FORWARD:将当前页面压入后向堆栈的顶部;从前向堆栈的顶部弹出该页,使其成为新的当前页。如果前向堆栈为空,则该指令忽略。

   VISIT:将当前页面压入后向堆栈的顶部,将URL指定为新的当前页。前向堆栈被清空。

   QUIT:退出浏览器。

   假设浏览器最初在网址http://www.game.org/上加载网页。

【输入形式】输入是一个命令序列。命令关键字BACK、FORWARD、VISIT和QUIT都是大写。URL中无空格,最多有70个字符。假定在任何时候,每个堆栈中没有问题实例需要超过100个元素。输入的结尾由QUIT命令标识。

【输出形式】除QUIT外的每个命令,如果命令没有被忽略,则在命令执行后输出当前页面的URL,否则,打印”Ignored”。每个命令的输出独立打印一行。QUIT命令无输出。

【样例输入】

VISIT http://game.ashland.edu/
VISIT http://game.baylor.edu/acmicpc/
BACK
BACK
BACK
FORWARD
VISIT http://www.our.com/
BACK
BACK
FORWARD
FORWARD
FORWARD
QUIT

【样例输出】

http://game.ashland.edu/

http://game.baylor.edu/acmicpc/

http://game.ashland.edu/

http://www.game.org/

Ignored

http://game.ashland.edu/

http://www.our.com/

http://game.ashland.edu/

http://www.game.org/

http://game.ashland.edu/

http://www.our.com/

Ignored



思路:
将第n个访问过的网站看做第n个暗箱。箱子不变,但箱子里装的东西有可能变(前进+后退+突然VISIT访问了其它网站改变了顺序,顶替了原来这个箱子里面的网站。此时全新的顺序产生,并且原来此位置以后的箱子全部清空,原来存储的网站无效)
这里写图片描述



#include<iostream>
using namespace std;
int main()
{
    string visited[100];
    int step=0;
    int flag[100]={0};
    int cnt=1;
    visited[0]="http://www.game.org/";
    flag[0]=1;
    string str;
    while(getline(cin,str)&&str!="QUIT")
    {
        if(str.substr(0,5)=="VISIT")
        {
            step++;
            if(flag[step]==0)
            {
                int len=str.length();
                visited[step]=str.substr(6,(len-6));
                cout<<visited[step]<<endl;
                flag[step]=1;
                cnt++;
            }
            else
            {
                int len=str.length();
                visited[step]=str.substr(6,(len-6));
                cout<<visited[step]<<endl;
                for(int i=step;i<cnt;i++)
                {
                    flag[i]=0;
                }
                flag[step]=1;
                cnt=step+1;
            }
        }
        else if(str=="BACK")
        {
            step--;
            if(step>=0)
            {
                cout<<visited[step]<<endl;
            }
            else
            {
                step++;
                cout<<"Ignored"<<endl;
            }
        }
        else if(str=="FORWARD")
        {
            step++;
            if(step<=(cnt-1))
            {
                cout<<visited[step]<<endl;
            }
            else
            {
                step--;
                cout<<"Ignored"<<endl;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lzydadong/article/details/82462515
今日推荐