PAT 1178 File Path
作者:
NikoNairre
,
2023-11-29 16:31:38
,
所有人可见
,
阅读 152
C++
#include <iostream>
#include <stack>
#include <algorithm>
#include <string.h>
#include <vector>
using namespace std;
const int N = 1010, INF = 0x3f3f3f3f;
stack<int> level[N]; //use stack to find the father of current floder quickly
int pre[10010]; //locate path, since id are all 4-digit nums, we set size to 1e4
int n, k;
int main()
{
memset(pre, 0x3f, sizeof(pre)); //pre[i] = INF means this node donesn't exist
scanf("%d", &n);
getchar();
pre[0] = -1; //note the pre of root 0000 as -1, which tells the difference from thoses pre[]=INF
for (int i = 0; i < n; i++ ) {
string cid;
getline(cin, cid);
int l = count(cid.begin(), cid.end(), ' '); //count spaces int cid, we can judge the level of its position
int id = stoi(cid); //stored in number format
level[l].push(id); //put to current level's stacks
if (l > 0) { //not the root floder
int last = level[l - 1].top(); //search the last level's stack's top to find the father
pre[id] = last; //last->id, record path
}
}
scanf("%d", &k);
while (k-- ) {
int id; scanf("%d", &id);
if (pre[id] == INF) { //this floder doesn't exist
printf("Error: %04d is not found.", id);
}
else {
vector<int> path; //record path in reversed order
while (id != -1) {
path.push_back(id);
id = pre[id];
}
for (int i = path.size() - 1; i >= 0; i-- ) { //reprint in natural order
printf("%04d", path[i]);
if (i) printf("->");
}
}
if (k) puts("");
}
// string s = " 12";
// cout << stoi(s) << endl;
return 0;
}