PTA甲级
1174 Left-View of Binary Tree
#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>using namespace std;const int N = 1e5 + 10;
int pre[N] , in[N] , idx[N] , l[N] , r[N];
int n , max_dep = 0;
unordered_map<int , vector<int>>mp;int build(int il , int ir , int pl , int pr , int dep)
{int root = pre[pl];int k = idx[root];mp[dep].push_back(root);max_dep = max(max_dep , dep);if(il < k) l[root] = build(il , k - 1 , pl + 1 , pl + k - il , dep + 1);if(ir > k) r[root] = build(k + 1 , ir , pl + k - il + 1 , pr , dep + 1);return root;
}int main()
{cin >> n;for(int i = 0;i < n;i ++) cin >> in[i] , idx[in[i]] = i;for(int i = 0;i < n;i ++) cin >> pre[i];int root = build(0 , n - 1 , 0 , n - 1 , 0);for(int i = 0;i <= max_dep;i ++){if(i) cout << " ";cout << mp[i][0];}return 0;
}
1176 The Closest Fibonacci Number
#include<iostream>using namespace std;const int N = 50;
typedef long long ll;
ll f[N] , n;int main()
{cin >> n;f[0] = 0 , f[1] = 1;for(int i = 2;i < N;i ++)f[i] = f[i - 1] + f[i - 2];ll closest = 0 , be = 0x3f3f3f3f3f;for(int i = 0;i < N;i ++)if(be > abs(f[i] - n)) closest = f[i] , be = abs(f[i] - n);cout << closest << endl;return 0;
}
1177 Subsequence in Substring
#include<iostream>using namespace std;string s , t;
int res = 0x3f3f3f3f3f;
string ans;int main()
{cin >> s >> t;for(int i = 0;i <= s.size() - t.size();i ++){int j = 0 , h = i;for(h = i;h < s.size() && j < t.size();h ++)if(s[h] == t[j]) j ++;if(j == t.size()) {if(h - i < res){res = h - i;ans = s.substr(i , h - i);}}}cout << ans;return 0;
}
1178 File Path
#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
#include<set>using namespace std;int n;
unordered_map<int , set<string>>mp;
unordered_map<int , vector<string>>mp1;
unordered_map<string , int>idx;
unordered_map<int , string>last;
int len = 0x3f3f3f3f3f;void check(string x , string& res)
{vector<string>path;while(x != "0000"){path.push_back(x);x = last[idx[x]];}for(int i = path.size() - 1;i >= 0;i --)res = res + "->" + path[i];
}int main()
{cin >> n;getchar();int cnt = 0;while(n --){string s;getline(cin , s);int d = 0 , i = 0;while(i < s.size() && s[i] == ' ') i ++ , d ++;mp[d].insert(s.substr(i));mp1[d].push_back(s.substr(i));idx[s.substr(i)] = cnt;if(d) last[cnt ++] = mp1[d - 1].back();}int k;cin >> k;while(k --){string x;cin >> x;string res;if(idx.count(x)) {string res = "0000";check(x , res);cout << res << endl;}else printf("Error: %s is not found.\n" , x.c_str());}return 0;
}