-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathhappy-vertices.java
74 lines (70 loc) · 2.17 KB
/
happy-vertices.java
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
// https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/happy-vertices/
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/*
The problem is simple implementation of DFS while maintaining a count of children
of the vertices visited. Let u be a vertex and v be its child. Then, check if
children[v]>children[u].This way, check for each vertex while traversing the graph in DFS.
One important thing to note that actually there are many trees in the input(a graph with
no cycles and self loops is a tree). That means , you have to apply DFS for each of these trees.
*/
class Ideone
{
static int[] parent;
static int[] children;
static boolean[] visited;
static List<List<Integer>> nodes;
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
nodes = new ArrayList<List<Integer>>();
parent = new int[n+1];
children = new int[n+1];
visited = new boolean[n+1];
for (int i = 0; i <= n; i++) nodes.add(new ArrayList<Integer>());
for (int i = 0; i < m; i++) {
int x = sc.nextInt(), y = sc.nextInt();
nodes.get(x-1).add(y-1);
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
parent[i] = -1;
dfs(i);
}
}
int cnt = 0;
for (int i = 0; i <= n; i++)
if (parent[i] != -1)
if (children[i] > children[parent[i]]) cnt++;
System.out.println(cnt);
/**
* Another way to calculate is to find all the happy vertices and subtract
* the master vertex. In each connected component, there is only one
* master vertex.
* int cnt = 0, ans = 0;
* for (int i = 1; i <= n; i++) {
* cnt++;
* if (!visited[i]) dfs(i);
* }
* for (int i = 1; i <= n; i++) {
* // if i is a master vertext, then parent[i] = 0, children[0] = 0, so ans in automatically
* // incremented.
* if (children[i] > children[parent[i]]) ans++;
* }
* System.out.println(cnt-ans);
* */
}
public static void dfs(int u) {
visited[u] = true;
for (int v : nodes.get(u)) {
if (!visited[v]) {
children[u]++;
parent[v] = u;
dfs(v);
}
}
}
}