算法每一题,成长每一天~
C0E44 We Are A Team
真题链接:【持续更新】2024华为 OD 机试E卷 机考真题库清单(全真题库)
思路
1、使用 Map<key, Set<>> 记录每个成员的team成员
Java
package com.ccr.paper_f;
import java.util.*;
public class C0E44 {
static Set<Integer> EMPTY = new HashSet<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[][] arr = new int[m][3];
Map<Integer, Set<Integer>> map = new HashMap<>(); // 记录同组信息
for (int i = 0; i < m; i++) {
int a = arr[i][0] = in.nextInt();
int b = arr[i][1] = in.nextInt();
int c = arr[i][2] = in.nextInt();
if (c == 0) {
Set<Integer> combine = new HashSet<>();
combine.addAll(map.getOrDefault(a, EMPTY));
combine.addAll(map.getOrDefault(b, EMPTY));
combine.add(a);
combine.add(b);
for (Integer integer : combine) {
map.put(integer, combine); // 每次全量更新 team 成员
}
}
}
for (int[] line : arr) {
if (line[2] == 0) {
continue;
} else if (line[2] == 1) {
if (map.get(line[0]).contains(line[1])) {
System.out.println("we are a team");
} else {
System.out.println("we are not a team");
}
} else {
System.out.println("da pian zi");
}
}
}
}
总结
~
算法要多练多练多练!!