7-3 File Path (25 分)
The figure shows the tree view of directories in Windows File Explorer. When a file is selected, there is a file path shown in the above navigation bar. Now given a tree view of directories, your job is to print the file path for any selected file.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤103), which is the total number of directories and files. Then N lines follow, each gives the unique 4-digit ID of a file or a directory, starting from the unique root ID 0000
. The format is that the files of depth d will have their IDs indented by d spaces. It is guaranteed that there is no conflict in this tree structure.
Then a positive integer K (≤100) is given, followed by K queries of IDs.
Output Specification:
For each queried ID
, print in a line the corresponding path from the root to the file in the format: 0000->ID1->ID2->...->ID
. If the ID
is not in the tree, print Error: ID is not found.
instead.
Sample Input:
14
0000
1234
2234
3234
4234
4235
2333
5234
6234
7234
9999
0001
8234
0002
4 9999 8234 0002 6666
结尾无空行
Sample Output:
0000->1234->2234->6234->7234->9999
0000->1234->0001->8234
0000->0002
Error: 6666 is not found.
结尾无空行
思路:使用cnt来记录层级(string的长度),使用vector ans来模拟堆栈,记录访问,层级不对就pop直到cnt符合
AC代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
int num;
vector<int> next;
};
int N,K;
vector<int> ans;
int main(){
cin>>N;
getchar();
vector<string> v(N);
for(int i=0;i<N;i++){
getline(cin,v[i]);
}
cin>>K;
for(int i=0;i<K;i++){
int tag;
scanf("%d",&tag);
int cnt=4;
ans.clear();
bool flag=false;
for(int j=0;j<N;j++){
if(stoi(v[j])==tag){
for(int m=0;m<(cnt-v[j].size());m++){
ans.pop_back();
}
ans.push_back(tag);
flag=true;
break;
}else{
if(cnt==v[j].size()){
ans.push_back(stoi(v[j]));
cnt++;
}else{
for(int m=0;m<(cnt-v[j].size());m++){
ans.pop_back();
}
ans.push_back(stoi(v[j]));
cnt=v[j].size()+1;
}
}
}
if(flag){
for(int j=0;j<ans.size();j++){
if(j==0){
printf("%04d",ans[j]);
}else{
printf("->%04d",ans[j]);
}
}
printf("\n");
}else{
printf("Error: %d is not found.\n",tag);
}
}
return 0;
}