CodeForces - 158C(模擬)

題意

https://vjudge.net/problem/CodeForces-158Cios

你須要實現相似 Unix / Linux 下的 cd 和 pwd 命令。c++

一開始,用戶處於根目錄 / 下。spa

對於 cd 命令,它的做用是跳轉到某個路徑。路徑有相對路徑和絕對路徑,相對路徑以文件夾名開頭,表示當前目錄下的文件夾,絕對路徑以 / 開頭,表示根目錄下的文件夾。同時,.. 文件夾表示上一層文件夾。.net

對於 pwd 命令,你須要輸出當前所在的絕對路徑。code

保證輸入數據中全部的文件夾都存在。blog

思路

用棧記錄每次往下搜索的文件夾,先對cd後面的字符串加一個"/",每次遇到../就退回上一級目錄(pop)。ci

具體看代碼。字符串

代碼

#include <bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int N = 200005;
const int mod = 1e9 + 7;
#define lowbit(x) (x & (-x))
int main()
{
    std::ios::sync_with_stdio(false);
    int n;
    cin >> n;
    stack<string> st, st2;
    while (n--)
    {
        string s;
        cin >> s;
        if (s[0] == 'p')
        {
            cout << "/";
            while (!st.empty())
            {
                st2.push(st.top());
                st.pop();
            }
            while (!st2.empty())
            {
                st.push(st2.top());
                cout << st2.top();
                st2.pop();
            }
            cout << endl;
        }
        else
        {
            string cur = "";
            cin >> s;
            s += '/';
            int l = s.length();
            for (int i = 0; i < l; i++)
            {
                cur += s[i];
                if (s[i] == '/')
                {
                    if (cur == "/")
                    {
                        while (!st.empty())
                            st.pop();
                    }
                    else if (cur == "../")
                    {
                        st.pop();
                    }
                    else
                    {
                        st.push(cur);
                    }
                    cur = "";
                }
            }
        }
    }
    return 0;
}
相關文章
相關標籤/搜索