Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions src/main/java/problemset/a3607/PowerGridMaintenance.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package problemset.a3607;

import java.util.*;

public class PowerGridMaintenance {
Map<Integer, List<Integer>> adj = new HashMap<>();
Set<Integer> online = new HashSet<>();
Map<Integer, Integer> stationGroup = new HashMap<>();
Map<Integer, PriorityQueue<Integer>> minHeap = new HashMap<>();

public int[] processQueries(int c, int[][] connections, int[][] queries) {

for (int[] connection: connections) {
int u = connection[0];
int v = connection[1];

adj.computeIfAbsent(u, k -> new ArrayList<>()).add(v);
adj.computeIfAbsent(v, k -> new ArrayList<>()).add(u);
}

// build connected components
for (int s = 1; s < c + 1; s++) {
dfs(s, s);
}

List<Integer> gather = new ArrayList<>();

for (int[] query : queries) {
int type = query[0];
int station = query[1];

if (type == 1) {
if (online.contains(station)) {
gather.add(station);
continue;
}
int groupId = stationGroup.get(station);
PriorityQueue<Integer> pq = minHeap.get(groupId);
while (pq != null && !pq.isEmpty() && !online.contains(pq.peek())) {
pq.poll();
}
if (!pq.isEmpty()) {
gather.add(pq.peek());
} else {
gather.add(-1);
}
} else {
online.remove(station);
}
}

return gather.stream().mapToInt(Integer::intValue).toArray();
}

private void dfs(int station, int groupId) {
if (online.contains(station))
return;

online.add(station);
stationGroup.put(station, groupId);
minHeap.computeIfAbsent(groupId, k -> new PriorityQueue<>()).add(station);

for (int nei : adj.getOrDefault(station, new ArrayList<>())) {
dfs(nei, groupId);
}
}
}
41 changes: 41 additions & 0 deletions src/test/java/problemset/a3607/PowerGridMaintenanceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package problemset.a3607;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class PowerGridMaintenanceTest {

private PowerGridMaintenance powerGridMaintenance;
private int c1;
private int[][] connections1;
private int[][] queries1;


@BeforeEach
void setUp() {
powerGridMaintenance = new PowerGridMaintenance();
c1 = 5;
connections1 = new int[][]{
{1, 2},
{2, 3},
{3, 4},
{4, 5}
};
queries1 = new int[][]{
{1, 3},
{2, 1},
{1, 1},
{2, 2},
{1, 2}
};
}

@Test
void test_processQueries() {
int[] expected = new int[]{3, 2, 3};
int[] actual = powerGridMaintenance.processQueries(c1, connections1, queries1);
assertArrayEquals(expected, actual);
}
}
Loading