题目描述
https://www.nowcoder.com/discuss/596753970027085824
题目描述
为了达到新冠疫情精准防控的需要,为了避免全员核酸检测带来的浪费,需要精准圈定可能被感染的人群。
现在根据传染病流调以及大数据分析,得到了每个人之间在时间、空间上是否存在轨迹的交叉。
现在给定一组确诊人员编号(X1,X2,X3…Xn) 在所有人当中,找出哪些人需要进行核酸检测,输出需要进行核酸检测的人数。(注意:确诊病例自身不需要再做核酸检测)
需要进行核酸检测的人,是病毒传播链条上的所有人员,即有可能通过确诊病例所能传播到的所有人。
例如:A是确诊病例,A和B有接触、B和C有接触 C和D有接触,D和E有接触。那么B、C、D、E都是需要进行核酸检测的
输入描述
第一行为总人数N
第二行为确诊病例人员编号 (确证病例人员数量 < N) ,用逗号隔开
接下来N行,每一行有N个数字,用逗号隔开,其中第i行的第个j数字表名编号i是否与编号j接触过。0表示没有接触,1表示有接触
输出描述
输出需要做核酸检测的人数
补充说明
人员编号从0开始, 0 < N < 100
示例1
输入:
5
1,2
1,1,0,1,0
1,1,0,0,0
0,0,1,0,1
1,0,0,1,0
0,0,1,0,1
输出
3
说明:
编号为1、2号的人员为确诊病例1号与0号有接触,0号与3号有接触,2号54号有接触。所以,需要做核酸检测的人是0号、3号、4号,总计3人要进行核酸检测。
题解
并查集:https://zhuanlan.zhihu.com/p/93647900
public class Precision_Nucleic_Acid_Detection {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = Integer.parseInt(scanner.nextLine());
// 确诊人员编号
int[] confirmed = Arrays.stream(scanner.nextLine().split(",")).mapToInt(Integer::parseInt).toArray();
HashSet<Integer> confirmedSet = new HashSet<>();
for (int i : confirmed) {
confirmedSet.add(i);
}
// 读取接触情况,构建并查集
UnionFind unionFind = new UnionFind(N);
int[][] contact = new int[N][N];
for (int i = 0; i < N; i++) {
String[] line = scanner.nextLine().split(",");
for (int j = 0; j < N; j++) {
contact[i][j] = Integer.parseInt(line[j]);
if (contact[i][j] == 1) {
unionFind.union(i, j);
}
}
}
// 统计需要核酸检测人数
Set<Integer> needTest = new HashSet<>();
for (int person : confirmed) {
int root = unionFind.find(person);
for (int i = 0; i < N; i++) {
if (unionFind.find(i) == root && !confirmedSet.contains(i)) {
needTest.add(i);
}
}
}
// 输出需要核酸检测的人数
System.out.println(needTest.size());
scanner.close();
}
// 并查集
static class UnionFind {
private int[] parent;
private int[] rank;
public UnionFind(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
}
}
public int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
// 按秩合并
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP != rootQ) {
if (rank[rootP] > rank[rootQ]) {
parent[rootQ] = rootP;
} else if (rank[rootP] < rank[rootQ]) {
parent[rootP] = rootQ;
} else {
parent[rootQ] = rootP;
rank[rootP]++;
}
}
}
}
}