题目:http://codeforces.com/problemset/problem/158/C
C. Cd and pwd commands
time limit pertest
memory limit pertest
input
output
Vasya is writing anoperating system shell, and it should have commands for workingwith directories. To begin with, he decided to go with just twocommands:
Directories inVasya's operating system form a traditional hierarchical treestructure. There is a single root directory, denoted by the slashcharacter "/". Every other directory has a name — a non-emptystring consisting of lowercase Latin letters. Each directory(except for the root) has a parent directory — the one thatcontains the given directory. It is denoted as "..".
Thecommand
Thecommand
Initially, thecurrent directory is the root. All directories mentioned explicitlyor passed indirectly within anycommand
Input
The first line of theinput data contains the singleinteger
Thenfollow
The commandparameter
Directories in thefile system can have the same names.
Output
For eachcommand
Sample test(s)
input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
output
/
/home/vasya/
/home/
/home/petya/
input
4
cd /a/b
pwd
cd ../a/b
pwd
output
/a/b/
/a/a/b/
原文:http://www.xuebuyuan.com/576977.html
解题说明:这题模拟了linux下对文件路径的操作,包括.. /这些符号的使用。按照题目要求,肯定是输入一条数据就处理一条数据,处理的意思就是确定当前的路径。一个很容易想到的方法是用树来实现,不过用在这种题目上过于复杂了。这题完全可以用string来模拟,用一个string来保存当前的路径,中间用/隔开,当出现../时回退到上一个/所在处,否则就把读取到的值放入string,可能是覆盖或是拼接。
#include <iostream>
#include<string>
using namespace std;
int main()
{
string temp,pr,st; //temp用来保存当前截取的字符串,pr用于输出,st用于输入
int i,j,n,len;
scanf("%d",&n);
pr="/"; //pr初始化
temp=""; //temp初始化
while (n--)
{
cin>>st;
if (st=="cd")
{
cin>>st;
st+='/';
len=st.length();
for (i=0;i<len;i++)
{
temp+=st[i]; //每次截取st子字符串,遇到'/'时停下
if (st[i]=='/')
{
if (temp=="/") //初始化pr为根目录
pr=temp;
else
if (temp=="../") //返回上级目录
{
for (j=pr.length()-1;pr[j-1]!='/';j--);
pr.resize(j);
}
else
pr+=temp;
temp="";
}
}
}
else
cout<<pr<<endl;
}
return 0;
}
注意事项:
string是类,不能使用printf输出,printf()只能打印基本类型。
应该用
string s;
cout << s;
或
printf("%s", s.c_str()); //不推荐