-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathC.txt
65 lines (60 loc) · 1.83 KB
/
C.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import static java.lang.System.out;
import java.util.ArrayList;
import java.util.Scanner;
public class C {
static ArrayList<Integer>[] graph;
static int[] length;
static boolean[] leaf;
static boolean[] visited;
static double[] prob;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<Integer>();
}
length = new int[n];
leaf = new boolean[n];
visited = new boolean[n];
prob = new double[n];
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
graph[u].add(v);
graph[v].add(u);
}
prob[0] = 1;
dfs(0, 0);
double result = 0.0;
for (int i = 0; i < n; i++) {
if (leaf[i]) {
result += prob[i] * length[i];
}
}
System.out.println(result);
}
public static void dfs(int v, int len) {
boolean isLeaf = true;
visited[v] = true;
int total = graph[v].size();
int alreadyVisited = 0;
for (int i = 0; i < graph[v].size(); i++) {
int to = graph[v].get(i);
if (visited[to]) {
alreadyVisited += 1;
}
}
for (int i = 0; i < graph[v].size(); i++) {
int to = graph[v].get(i);
if (!visited[to]) {
prob[to] = prob[v] * 1.0 / (total - alreadyVisited);
visited[to] = true;
length[to] = len + 1;
isLeaf = false;
dfs(to, len + 1);
}
}
leaf[v] = isLeaf;
}
}