1 条题解
-
0
JAVA题解:
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] line = br.readLine().trim().split(" "); int N = Integer.parseInt(line[0]); // 设备总量 int M = Integer.parseInt(line[1]); // 互斥设备数量 int X = Integer.parseInt(line[2]); // 指令数量 // 读取互斥设备编号 line = br.readLine().trim().split(" "); int[] mutexDevices = new int[M]; for (int i = 0; i < M; i++) { mutexDevices[i] = Integer.parseInt(line[i]); } // 读取连接指令 int[][] commands = new int[X][2]; for (int i = 0; i < X; i++) { line = br.readLine().trim().split(" "); commands[i][0] = Integer.parseInt(line[0]); commands[i][1] = Integer.parseInt(line[1]); } // 计算并输出结果 int result = countRejectedCommands(N, mutexDevices, commands); System.out.println(result); } public static int countRejectedCommands(int N, int[] mutexDevices, int[][] commands) { DisjointSetUnion dsu = new DisjointSetUnion(N); // 标记互斥设备 for (int device : mutexDevices) { dsu.blocked[dsu.find(device)] = true; } int rejectedCount = 0; // 处理每条连接指令 for (int[] command : commands) { int u = command[0]; int v = command[1]; int rootU = dsu.find(u); int rootV = dsu.find(v); // 如果两个设备的根都是互斥设备,则拒绝执行 if (rootU != rootV && dsu.blocked[rootU] && dsu.blocked[rootV]) { rejectedCount++; } else { dsu.unite(u, v); } } return rejectedCount; } static class DisjointSetUnion { private int[] parent; private int[] size; boolean[] blocked; // 标记互斥设备的根 public DisjointSetUnion(int n) { parent = new int[n]; size = new int[n]; blocked = new boolean[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; blocked[i] = false; } } // 查找元素所属集合的根 public int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); // 路径压缩 } return parent[x]; } // 合并两个集合 public void unite(int a, int b) { int rootA = find(a); int rootB = find(b); if (rootA == rootB) { return; } // 按秩合并,将较小的树连接到较大的树上 if (size[rootA] < size[rootB]) { int temp = rootA; rootA = rootB; rootB = temp; } parent[rootB] = rootA; size[rootA] += size[rootB]; blocked[rootA] = blocked[rootA] || blocked[rootB]; // 更新互斥标记 } } }
- 1
信息
- ID
- 26
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 5
- 标签
- 递交数
- 7
- 已通过
- 1
- 上传者