1 #include <bits/stdc++.h> 2 #define INF 0x3f3f3f3f 3 #define ll long long 4 using namespace std; 5 int n, f[300010], head[300010], num; 6 struct node {int next, to;}stu[600010]; 7 void add(int x, int y) {stu[++num].next = head[x]; stu[num].to = y; head[x] = num; return;} 8 int main() 9 { 10 scanf("%d", &n); 11 for(int i = 1, x, y; i < n; ++i) 12 { 13 scanf("%d%d", &x, &y); 14 add(x, y), add(y, x); 15 } 16 ll ans = 0; 17 for(int u = 1; u <= n; ++u) 18 { 19 for(int i = head[u]; i; i = stu[i].next) 20 { 21 int x = stu[i].to; 22 if(x < u) f[u] += f[x] + 1; 23 } 24 for(int i = head[u]; i; i = stu[i].next) 25 { 26 int x = stu[i].to; 27 if(x < u) ans += (ll)(f[u] - f[x] - 1) * (f[x] + 1); 28 } 29 } 30 printf("%lld", ans); 31 return 0; 32 }
#include <bits/stdc++.h>#define INF 0x3f3f3f3f#define ll long longusing namespace std;int n, f[300010], head[300010], num;struct node {int next, to;}stu[600010];void add(int x, int y) {stu[++num].next = head[x]; stu[num].to = y; head[x] = num; return;}int main(){scanf("%d", &n);for(int i = 1, x, y; i < n; ++i){scanf("%d%d", &x, &y);add(x, y), add(y, x);}ll ans = 0;for(int u = 1; u <= n; ++u){for(int i = head[u]; i; i = stu[i].next){int x = stu[i].to;if(x < u) f[u] += f[x] + 1;}for(int i = head[u]; i; i = stu[i].next){int x = stu[i].to;if(x < u) ans += (ll)(f[u] - f[x] - 1) * (f[x] + 1);}}printf("%lld", ans);return 0;}