【非原創】codeforces 1060E Sergey and Subway 【樹上任意兩點距離和】
阿新 • • 發佈:2018-11-04
學習部落格:戳這裡
本人程式碼:
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 = 1View Code; 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 }