Guest User

Component Tree

a guest
Dec 3rd, 2017
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define F first
  3. #define S second
  4. using namespace std;
  5. typedef long long ll;
  6. const int maxx = 3e5 + 4;
  7.  
  8. int n, par, k, q;
  9. string s;
  10. std::map<string, string> tree[maxx * 4], a[maxx];
  11. int index[maxx];
  12. std::vector<int> g[maxx];
  13.  
  14. void upd(int x, int y, string key, string value, int id = 1, int l = 0, int r = n){
  15.     if(x >= r or y <= l) return;
  16.     if(x <= l and r <= y){
  17.         if(tree[id][key] == "")
  18.             tree[id][key] = value;
  19.         return;
  20.     }
  21.     int mid = (l + r) / 2;
  22.     upd(x, min(mid, y), key, value, id * 2, l, mid);
  23.     upd(max(mid, x), y, key, value, id * 2 + 1, mid, r);
  24. }
  25.  
  26. string query(int pos, string key, int id = 1, int l = 0, int r = n){
  27.     if(r - l < 2){
  28.         if(tree[id][key] != "")
  29.             return tree[id][key];
  30.         else
  31.             return "N/A";
  32.     }
  33.     int mid = (l + r) / 2;
  34.     string s1 = "", s2 = "";
  35.     if(pos < mid)
  36.         s1 = query(pos, key, id * 2, l, mid);
  37.     else
  38.         s2 = query(pos, key, id * 2 + 1, mid, r);
  39.     if(s1 == "N/A" or s2 == "N/A"){
  40.         if(tree[id][key] != "")
  41.             return tree[id][key];
  42.         else
  43.             return "N/A";
  44.     }
  45.     return s1 + s2;
  46. }
  47.  
  48. int dfs(int x, int par, int cnt){
  49.     index[x] = cnt;
  50.     for(auto i: g[x]){
  51.         if(i != par)
  52.             cnt = dfs(i, x, cnt + 1);
  53.     }
  54.     for(auto i: a[x]){
  55.         upd(index[x], cnt + 1, i.F, i.S);
  56.     }
  57.     return cnt;
  58. }
  59.  
  60. int main(){
  61.     cin>>n;
  62.     for (int i = 1; i <= n; ++i)
  63.     {
  64.         cin>>par>>k;
  65.         g[i].push_back(par);
  66.         g[par].push_back(i);
  67.         for(int j = 0; j < k; j++){
  68.             cin>>s;
  69.             int pos = s.find("=");
  70.             string key = s.substr(0, pos);
  71.             string value = s.substr(pos+1, string::npos);
  72.             a[i][key] = value;
  73.         }
  74.     }
  75.     dfs(1, 0, 0);
  76.     cin>>q;
  77.     int c;
  78.     string name;
  79.     for (int i = 0; i < q; ++i)
  80.     {
  81.         cin>>c>>name;
  82.         cout<<query(index[c], name)<<endl;
  83.         fflush(stdout);
  84.     }
  85. }
Add Comment
Please, Sign In to add comment