classSolution { public: vector<int> ans, sz, dp; vector<vector<int>> graph;
// 以u为根,f为父节点的树状dp,获取dp[u]所有子节点到根的和 voiddfs(int u, int f){ // sz[u]=1 是一开始自身节点数为1 sz[u] = 1; dp[u] = 0; for (auto& v: graph[u]) { if (v == f) { continue; } dfs(v, u); dp[u] += dp[v] + sz[v]; sz[u] += sz[v]; } }
voiddfs2(int u, int f){ // ans[u] 就等于 u 为根时的dp值 ans[u] = dp[u]; for (auto& v: graph[u]) { if (v == f) { continue; } // 伪装成v为根,去获取ans[v]=dp[v]后恢复 int pu = dp[u], pv = dp[v]; int su = sz[u], sv = sz[v];
⚡ 07/12|11:30:32 test /usr/bin/g++ -fdiagnostics-color=always -g /root/code/test/tmp.cpp -o /root/code/test/tmp -lgtest -lpthread ⚡ 07/12|11:34:42 test ./tmp [==========] Running 1 test from 1 testcase. [----------] Global test environment set-up. [----------] 1 test from TestCaseName [ RUN ] TestCaseName.TestName [ OK ] TestCaseName.TestName (0 ms) [----------] 1 test from TestCaseName (0 ms total)
[----------] Global test environment tear-down [==========] 1 test from 1 testcase ran. (0 ms total) [ PASSED ] 1 test.
通过VScode使用
在 VSCode 中运行单元测试:打开命令面板(Ctrl+Shift+P),输入Debug: Start Without Debugging: