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

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

#include
#include
#include
#include
#include
#include
#include

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;
}

你可能感兴趣的:(算法,树结构,数据结构)