- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIndependent_Set.java
More file actions
Latest commit
64 lines (57 loc) · 1.55 KB
/
Copy pathIndependent_Set.java
File metadata and controls
64 lines (57 loc) · 1.55 KB
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
importjava.util.*;
importjava.io.*;
publicclassIndependent_Set {
publicstaticMap<Integer, LinkedList<Integer>> graph = newHashMap<>();
publicstaticlong[][] arr;
publicstaticintn;
publicstaticfinallongmod = 1000000007;
publicstaticlongrecurse(intcur, intparent, booleanblack) {
intcol = black ? 1 : 0;
if (arr[cur][col] != -1)
returnarr[cur][col];
LinkedList<Integer> temp = graph.get(cur);
longsum = 1;
if (black) {
for (intk : temp) {
if (k != parent) {
sum *= recurse(k, cur, false);
sum = sum % mod;
}
}
returnarr[cur][1] = sum;
} else {
for (intk : temp) {
if (k != parent) {
sum *= recurse(k, cur, false) + recurse(k, cur, true);
sum = sum % mod;
}
}
returnarr[cur][0] = sum;
}
}
publicstaticvoidmain(String[] args) throwsException {
BufferedReaderbr = newBufferedReader(newInputStreamReader(System.in));
n = Integer.parseInt(br.readLine()); //Bottom up method not possible. Children vary.
if (n == 1) {
System.out.println(2);
return;
}
arr = newlong[n + 1][2];
for (inti = 0; i < n + 1; i++)
Arrays.fill(arr[i], -1);
String[] s;
inta, b;
for (inti = 0; i < n - 1; i++) {
s = br.readLine().split(" ");
a = Integer.parseInt(s[0]);
b = Integer.parseInt(s[1]);
if (!graph.containsKey(a))
graph.put(a, newLinkedList<>());
if (!graph.containsKey(b))
graph.put(b, newLinkedList<>());
graph.get(a).add(b);
graph.get(b).add(a);
}
System.out.println((recurse(1, 0, true) + recurse(1, 0, false)) % mod);
}
}