2020PAT冬季考试甲级第三题文件树

不需要用到所有节点关系,所以非常规建树,简化了一些(附注释)
AC代码

#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<vector>

using namespace std;

int n, k;
string num[1002];
string fnum[102];
int lastdeppos[1002]; //记录父节点位置
int dep[1002];  //记录深度

void Findep(int pos){
	vector<string> filepos;
	//filepos.push_back(num[pos]);
	
	while(dep[pos] != 0){
		if(lastdeppos[pos] != -1){  //如果已知父节点,就不用再历遍找了
			filepos.push_back(num[pos]);
			pos = lastdeppos[pos];
			//filepos.push_back(num[pos]);
		}
		for(int i = pos; i >= 0; i--){
			if(dep[i] < dep[pos]){
				lastdeppos[pos] = i;
				filepos.push_back(num[pos]);
				pos = i;
				break;
			}
		}
	}
	filepos.push_back(num[0]);
	int siz = filepos.size();
	for(int i = siz - 1; i >= 0; i--){
		cout << filepos[i];
		if(i != 0)cout << "->";
		//else cout << '\n';
	}	
}

int main()
{
	
	//scanf("%d", &n);
	char c;
	cin >> n;	
	int lastpos = 0;
	for(int i = 0; i < n; i++){		
		c = getchar();  //吃空格
		c = ' ';
		while(c == ' '){
			c = getchar();
			dep[i]++;
		}
		dep[i]--;
		//cout << dep[i] << endl;
		num[i] = c;
		
		string st;
		cin >> st;
		num[i] = c + st; //把多读的一个字符补回来
		//cout << num[i] << '\n';
		lastdeppos[i] = -1;
		int len = num[i].length();		
		//cout << dep[i] << '\n';		
	}
	
	//scanf("%d", &k);
	cin >> k;
	for(int i = 0; i < k; i++){
		//scanf("%s", &fnum[i]);
		cin >> fnum[i];
	}
	
	for(int i = 0; i < k; i++){
		int j = 0;
		for(j = 0; j < n; j++){
			if(fnum[i] ==  num[j]){
				Findep(j);  //寻找所有的上层节点
				break;
			}
		}
		if(j >= n){
			cout << "Error: "<< fnum[i] <<" is not found.";
		}
		if(i != k - 1)cout << '\n';
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值