/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
{
// your code goes here
}
public int minimizeInfectionBruteForce(int n, int[] from, int[] to, int[] infected) {
int finalAnswer
= Integer.
MAX_VALUE; int minInfectedAfterSpread
= Integer.
MAX_VALUE;
// Try removing each node
for (int remove = 0; remove < n; remove++) {
// Step 1: Build new graph without 'remove'
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < from.length; i++) {
int u = from[i];
int v = to[i];
if (u == remove || v == remove) continue;
graph[u].add(v);
graph[v].add(u);
}
boolean[] visited = new boolean[n];
int infectedAfterSpread = 0;
// Step 2: DFS each component
for (int i = 0; i < n; i++) {
if (i == remove) continue;
if (!visited[i]) {
int[] result = dfs(i, remove, graph, visited, infected);
int componentSize = result[0];
int infectedCount = result[1];
if (infectedCount > 0) {
infectedAfterSpread += componentSize;
}
}
}
// Step 3: Track best removal
if (infectedAfterSpread < minInfectedAfterSpread) {
minInfectedAfterSpread = infectedAfterSpread;
finalAnswer = remove;
} else if (infectedAfterSpread == minInfectedAfterSpread) {
finalAnswer
= Math.
min(finalAnswer, remove
); }
}
return finalAnswer;
}
private int[] dfs(int node, int remove,
List<Integer>[] graph,
boolean[] visited,
int[] infected) {
Stack<Integer> stack = new Stack<>();
stack.push(node);
int componentSize = 0;
int infectedCount = 0;
while (!stack.isEmpty()) {
int curr = stack.pop();
if (visited[curr]) continue;
visited[curr] = true;
componentSize++;
if (infected[curr] == 1) {
infectedCount++;
}
for (int neighbor : graph[curr]) {
if (!visited[neighbor] && neighbor != remove) {
stack.push(neighbor);
}
}
}
return new int[]{componentSize, infectedCount};
}
}