题目链接:http://lightoj.com/volume_showproblem.php?problem=1357
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 #include <algorithm> 6 #include <vector> 7 using namespace std; 8 9 const int MAXN = (100000 + 10); 10 typedef long long ll; 11 int n; 12 ll child[MAXN]; 13 ll ans; 14 vector<int >g[MAXN]; 15 16 ll dfs(int u) 17 { 18 ll ret = 0; 19 for (int i = 0; i < (int)g[u].size(); i++) { 20 int v = g[u][i]; 21 dfs(v); 22 ans += ret * (child[v] + 1); 23 ret += child[v] + 1; 24 } 25 return child[u] = ret; 26 } 27 28 int main() 29 { 30 int _case, t = 1; 31 scanf("%d", &_case); 32 while (_case--) { 33 scanf("%d", &n); 34 for (int i = 1; i <= n; i++) g[i].clear(); 35 for (int i = 1; i < n; i++) { 36 int u, v; 37 scanf("%d %d", &u, &v); 38 g[u].push_back(v); 39 } 40 memset(child, 0, sizeof(child)); 41 ans = 0; 42 dfs(1); 43 printf("Case %d: %d %lld ", t++, n - 1, ans); 44 45 } 46 return 0; 47 }