-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBipartiteness.java
More file actions
78 lines (69 loc) · 2.03 KB
/
Bipartiteness.java
File metadata and controls
78 lines (69 loc) · 2.03 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* https://codeforces.com/problemset/problem/862/B tag: #dfs #graph #tree dfs and similar: create
* sets of graph, and check number of vertexes in set 2 that each vertex in set 1 can connect with.
*/
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
public class Bipartiteness {
public static void createPartSet(ArrayList<ArrayList<Integer>> graph, HashSet[] partSet) {
int startNode = 1;
int sz = graph.size();
boolean[] visitedArr = new boolean[sz];
Deque<Integer> dq = new LinkedList<Integer>();
dq.addLast(startNode);
visitedArr[startNode] = true;
partSet[0].add(startNode);
int setIdx, node;
while (!dq.isEmpty()) {
node = dq.pollLast();
if (partSet[0].contains(node)) {
setIdx = 0;
} else {
setIdx = 1;
}
for (Integer neighbour : graph.get(node)) {
if (!visitedArr[neighbour]) {
visitedArr[neighbour] = true;
partSet[1 - setIdx].add(neighbour);
dq.add(neighbour);
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sz = n + 1;
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i < sz; i++) {
graph.add(new ArrayList<Integer>());
}
int u, v;
for (int i = 0; i < n - 1; i++) {
u = sc.nextInt();
v = sc.nextInt();
graph.get(u).add(v);
graph.get(v).add(u);
}
// create bipartiteness
HashSet<Integer>[] partSet = new HashSet[2];
partSet[0] = new HashSet<>();
partSet[1] = new HashSet<>();
createPartSet(graph, partSet);
// count the number of edges can be added.
int setIdx;
if (partSet[0].size() <= partSet[1].size()) {
setIdx = 0;
} else {
setIdx = 1;
}
long ans = 0;
for (int node : partSet[setIdx]) {
ans += n - 1 - (partSet[setIdx].size() - 1) - graph.get(node).size();
}
System.out.println(ans);
}
}