PAT 2020年冬季 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 (≤10​3​​), 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.

实现思路:

现在pat的趋势就是字符串+逻辑题在增加,本题是一个树形结构的文件目录路径,最好的办法就是按照空格的个数看作是结点在树种的高度,然后建立当前结点的父节点,只要是空格少一个的数就是空格多一个的数的父结点,这里要注意一个细节,每次都要更新处于同一层的最后一个数的数据,仔细看一下样例就知道了。

AC代码:

#include <iostream>
#include <cstring>
#include <unordered_map>
using namespace std;
const int N=1010;
int last[N]= {0},pre[10010]= {0};
unordered_map<int,int> mp;

void dfs(int x) {
	if(x==0) {
		printf("0000");
		return;
	}
	dfs(pre[x]);
	printf("->%04d",x);
}

int main() {
	int n,k,id;
	cin>>n;
	getchar();
	string input;
	for(int i=0; i<n; i++) {
		getline(cin,input);
		int cnt=0;
		while(*input.begin()==' ') {
			input.erase(input.begin());
			cnt++;//计算前面有几个空格
		}
		int key=stoi(input);
		mp[key]=1;
		if(i==0) continue;
		pre[key]=last[cnt-1];//将上一层的最后结点设置为当前结点的父节点
		last[cnt]=key;//更新当前层的最后一个结点
	}
	cin>>k;
	int val;
	while(k--) {
		scanf("%d",&val);
		if(mp.count(val)==0) printf("Error: %04d is not found.",val);
		else dfs(val);
		printf("\n");
	}
	return 0;
}
posted @ 2021-03-11 18:26  coderJ_ONE  阅读(128)  评论(0编辑  收藏  举报