米哈游笔试D卷编程C题

#include <iostream>
#include <vector>
using namespace std;
const int N = 2e5 + 5;
using ll = long long;
struct node {
    int n;
    ll deep;
    ll ans;
};
vector<node> ans;
vector<vector<int>> g;

void dfs(int root, int fa = -1) {
    for (auto &to : g[root]) {
        if (to == fa) continue;
        dfs(to, root);
        ans[root].n += ans[to].n;
        ans[root].deep += ans[to].deep + ans[to].n;
    }
    ans[root].n += 1;
    for(auto &to : g[root]) {
        if (to == fa) continue;
        ans[root].ans += (ans[to].n + ans[to].deep) * (ans[root].n - ans[to].n) + ans[to].ans;
    }
}
int main() {
    int n, m;
    cin >> n >> m;
    g.resize(n + 1);
    ans.resize(n + 1);
    for (int i = 1; i < n; i++) {
        int u, v;
        cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    dfs(1);
    while(m--) {
        int x;
        cin >> x;
        cout << ans[x].ans << endl;
    }
    return 0;
}

笔试的时候 ans[root].ans += (ans[to].n + ans[to].deep) * (ans[root].n - ans[to].n) + ans[to].ans;忘记加ans[to].ans了,人麻了。

#米哈游笔试#
全部评论

相关推荐

评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务