最新华为OD机试
题目描述
总共有 n 个人在机房,每个人有一个标号(1<=标号<=n),他们分成了多个团队,需要你根据收到的 m 条消息判定指定的两个人是否在一个团队中,具体的:
- 消息构成为 a b c,整数 a、b 分别代表两个人的标号,整数 c 代表指令
- c == 0 代表 a 和 b 在一个团队内
- c == 1 代表需要判定 a 和 b 的关系,如果 a 和 b 是一个团队,输出一行’we are a team’,如果不是,输出一行’we are not a team’
- c 为其他值,或当前行 a 或 b 超出 1~n 的范围,输出‘da pian zi’
输入描述
- 第一行包含两个整数 n,m(1<=n,m<100000),分别表示有 n 个人和 m 条消息
- 随后的 m 行,每行一条消息,消息格式为:a b c(1<=a,b<=n,0<=c<=1)
输出描述
- c ==1,根据 a 和 b 是否在一个团队中输出一行字符串,在一个团队中输出‘we are a team‘,不在一个团队中输出’we are not a team’
- c 为其他值,或当前行 a 或 b 的标号小于 1 或者大于 n 时,输出字符串‘da pian zi‘
- 如果第一行 n 和 m 的值超出约定的范围时,输出字符串”Null“。
示例1
输入
5 7
1 2 0
4 5 0
2 3 0
1 2 1
2 3 1
4 5 1
1 5 1
12345678
输出
We are a team
We are a team
We are a team
We are not a team
1234
说明
示例2
输入
5 6
1 2 0
1 2 1
1 5 0
2 3 1
2 5 1
1 3 2
1234567
输出
we are a team
we are not a team
we are a team
da pian zi
1234
说明
解题思路
题目要求判断给定的两个人是否在同一个团队中。、
输入包含 n 个人和 m 条消息。
每条消息包含 a、b 和 c,其中 a 和 b 是两个人的标号,c 是指令。
- c == 0 表示 a 和 b 在同一个团队
- c == 1 表示需要判断 a 和 b 是否在同一个团队。
示例解释:
输入:
5 7
1 2 0
4 5 0
2 3 0
1 2 1
2 3 1
4 5 1
1 5 1
12345678
- 前三条消息表示:
- 1 和 2 在同一个团队
- 4 和 5 在同一个团队
- 2 和 3 在同一个团队
- 因此,团队关系如下:
- 团队1:1, 2, 3
- 团队2:4, 5
- 接下来的四条消息要求判断两个人是否在同一个团队:
- 1 和 2:在同一个团队(团队1),输出 “We are a team”
- 2 和 3:在同一个团队(团队1),输出 “We are a team”
- 4 和 5:在同一个团队(团队2),输出 “We are a team”
- 1 和 5:不在同一个团队,输出 “We are not a team”
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 读取输入,获取人数和消息数量
Scanner sc = new Scanner(System.in);
int numPeople = sc.nextInt();
int numMessages = sc.nextInt();
// 读取消息并存储到二维数组中
int[][] messages = new int[numMessages][3];
for (int i = 0; i < numMessages; i++) {
messages[i][0] = sc.nextInt();
messages[i][1] = sc.nextInt();
messages[i][2] = sc.nextInt();
}
// 检查输入范围,如果超出范围则输出 "Null"
if (numPeople < 1 || numPeople >= 100000 || numMessages < 1 || numMessages >= 100000) {
System.out.println("Null");
return;
}
// 初始化数组,用于存储每个人的团队信息
int[] parent = new int[numPeople + 1];
for (int i = 0; i < numPeople + 1; i++) parent[i] = i;
// 遍历消息,根据指令处理团队关系
for (int[] message : messages) {
int personA = message[0], personB = message[1], command = message[2];
// 检查输入范围,如果超出范围则输出 "da pian zi"
if (personA < 1 || personA > numPeople || personB < 1 || personB > numPeople) {
System.out.println("da pian zi");
continue;
}
// 如果指令为 0,则合并 personA 和 personB 所在的团队
if (command == 0) {
int rootA = find(personA, parent);
int rootB = find(personB, parent);
if