File tree Expand file tree Collapse file tree 1 file changed +79
-0
lines changed
Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+
3+ import java.util.* ;
4+ import java.io.* ;
5+
6+
7+ class Main {
8+
9+ // IO field
10+ static BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
11+ static BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (System . out));
12+ static StringTokenizer st;
13+
14+ static void nextLine () throws Exception {st = new StringTokenizer (br .readLine ());}
15+ static int nextInt() {return Integer . parseInt(st. nextToken());}
16+ static long nextLong() {return Long . parseLong(st. nextToken());}
17+ static void bwEnd() throws Exception {bw. flush();bw. close();}
18+
19+ // Additional field
20+
21+ static int N ;
22+ static List<Integer > [] V ;
23+ static long [] S ;
24+ static long ans = 0 ;
25+
26+ public static void main(String [] args) throws Exception {
27+
28+ ready();
29+ solve();
30+
31+ bwEnd();
32+
33+ }
34+
35+ static void ready() throws Exception {
36+
37+ N = Integer . parseInt(br. readLine());
38+ V = new List [N + 1 ];
39+ S = new long [N + 1 ];
40+ for (int i= 1 ;i<= N ;i++ ) V [i] = new ArrayList<> ();
41+ for (int i= 1 ;i< N ;i++ ) {
42+ nextLine();
43+ int a = nextInt(), b = nextInt();
44+ V [a]. add(b);
45+ V [b]. add(a);
46+ }
47+
48+ }
49+
50+ static void solve() throws Exception {
51+
52+ dfs(1 ,0 ,0 );
53+ bw. write(ans + " \n " );
54+
55+ }
56+
57+ static void dfs(int n, int p, long d) {
58+ S [n] = 1 ;
59+
60+ for (int i: V [n]) if (i != p) {
61+ dfs(i,n,d+ 1 );
62+ S [n] += S [i];
63+ ans += S [i] * (N - S [i]);
64+ }
65+
66+ long temp = 0 ;
67+ for (int i: V [n]) if (i != p) {
68+
69+ temp += S [i] * (S [n]- S [i]- 1 );
70+
71+ }
72+ temp = temp/ 2 + S [n]- 1 ;
73+ ans += temp * d;
74+
75+ }
76+
77+ }
78+
79+ ```
You can’t perform that action at this time.
0 commit comments