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 ($\leq 10^3$), which is the total number of directories and files. Then 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 will have their IDs indented by spaces. It is guaranteed that there is no conflict in this tree structure.
Then a positive integer () is given, followed by 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.
#include<iostream> #include<math.h> #include<vector> using namespace std; int N;//文件数量 int K;//查询的路径 struct Node { int depth; string name=""; string father=""; //vectorchild; }nodes[10000]; vector files;//保存文件名 vector root;//保存路径 int stringtoint(string str) { int ans = 0; int len = str.size(); for (int i = 0; i < 4; i++) { ans = ans + (str[len - i - 1] - '0') * pow(10, i); } return ans; } int main() { cin >> N; cin.ignore(); string index; int ind=0; for (int i = 0; i < N; i++) { getline(cin, index); ind = stringtoint(index); nodes[ind].name = index; nodes[ind].depth = nodes[ind].name.size() - 4;//深度,从0开始 files.push_back(ind); } for (int i = 1; i < N; i++) { for (int j = i-1; j >= 0; j--) {//从后往前找depth-1的第一个节点即此节点的父节点 if (nodes[files[i]].depth == (nodes[files[j]].depth + 1)) { nodes[files[i]].father = nodes[files[j]].name; break; } } } //for (int i = 0; i < N; i++) { // //printf("%s %04d\n", nodes[files[i]].name,nodes[files[i]].depth); // cout << nodes[files[i]].name << ' '; // printf("%04d\n", nodes[files[i]].depth); //} int K; cin >> K; int file; for (int i = 0; i < K; i++) { cin >> file; for (int i = 0; i < N; i++) { if (file == files[i]) { while (file != 0) { root.push_back(file); file = stringtoint((nodes[file].father)); } root.push_back(0); break; } } if (root.size() == 0) { printf("Error: %04d is not found.\n", file); } else { //cout << root.size(); for (int i = root.size()-1; i >=0; i--) { printf("%04d", root[i]); //cout << root[i]; if (i >0)cout << "->"; else cout << endl; } root.clear(); } } }
最新评论