[Source]
Question 2: Tree
[Analysis]
Build a tree model based on input conditions. The tree represents an array indicating Father's Day points. There are two core algorithms:
- Calculate the depth of a node. Use a loop to find the father's day point until the root node is found. The number of computing cycles is the depth.
- Calculates all subnodes of a node. Implement with recursion.
In the implementation of the node name from 0 to N-1, and the description of the subject is different.
[Code]
#include <iostream>#include <vector>using namespace std;vector<int> children(int node, int* father, int n){ vector<int> res; for (int i = 0; i < n; ++i){ if (father[i] == node){ res.push_back(i); vector<int> cs = children(i, father, n); if (cs.size() != 0){ for (int j = 0; j < cs.size(); ++j){ res.push_back(cs[j]); } } } } return res;}int main(){ int T; cin >> T; for (int c = 0; c < T; ++c){ int N; cin >> N; int* w = new int[N]; for (int i = 0; i < N; ++i){ w[i] = 0; } int* father = new int[N]; for (int i = 1; i < N; ++i){ cin >> father[i]; father[i]--; } // build the tree int* dep = new int[N]; dep[0] = 1; for (int i = 1; i < N; ++i){ int d = 1; int node = i; while (node != 0){ node = father[node]; ++d; } dep[i] = d; } int Q; cin >> Q; for (int i = 0; i < Q; ++i){ int u, l, r, delta; cin >> u >> l >> r >> delta; //do the operation vector<int> childs = children(u-1, father, N); for (int j = 0; j < childs.size(); ++j){ if (dep[childs[j]] >= l && dep[childs[j]] <= r){ w[childs[j]] += delta; } } } //calc hash int MOD = 1000000007; int MAGIC = 12347; int Hash = 0; for (int i = 0; i < N; ++i){ Hash = (Hash*MAGIC + w[i]) % MOD; } //output cout << "Case " << c+1 << ": " << Hash << endl; } system("pause"); return 0;}
[Comment]
This topic examines the knowledge of the tree and the design of recursive Programs. The focus is on computing the depth of a node and computing all the subnodes of a node.
[Remarks]
After this question is completed, the competition is just ready to be submitted. ==, there is no chance to submit the verification answer t. Code writing is very messy. If you have any questions, please leave a message.