【非原创】codeforces 1060E Sergey and Subway 【树上任意两点距离和】

学习博客:戳这里

本人代码:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 2e5 + 10;
 5 const ll mod = 998244353;
 6 vector<int> mp[maxn];
 7 ll ans = 0, cnt[3];
 8 int n;
 9 ll dfs(int u, int pre,int now) {
10     ++cnt[now];
11     ll siz = 1;
12     for(int i = 0; i < mp[u].size(); ++i) {
13         int v = mp[u][i];
14         if(v == pre) continue;
15         siz += dfs(v, u, now^1);
16     }
17     ans += siz * (n - siz);
18     return siz;
19 }
20 int main() {
21 
22 
23     scanf("%d", &n);
24     int u, v;
25     for(int i = 1; i < n; ++i) {
26         scanf("%d %d", &u, &v);
27         mp[u].push_back(v);
28         mp[v].push_back(u);
29     }
30     dfs(1,0,0);
31     printf("%lld\n", (ans + cnt[0] * cnt[1]) / 2);
32     return 0;
33 }
View Code

 

posted @ 2018-11-04 14:18  euzmin  阅读(165)  评论(0编辑  收藏  举报