> 文章列表 > 【华为OD机试真题 C++】1047 - We Are A Team | 机试题+算法思路+考点+代码解析

【华为OD机试真题 C++】1047 - We Are A Team | 机试题+算法思路+考点+代码解析

【华为OD机试真题 C++】1047 - We Are A Team | 机试题+算法思路+考点+代码解析

文章目录

    • 一、题目
      • 🔸题目描述
      • 🔸输入输出
      • 🔸样例1
      • 🔸样例2
    • 二、代码参考
  • 作者:KJ.JK

🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈
 
🍂个人博客首页: KJ.JK
 
💖系列专栏:华为OD机试真题(C++)


一、题目


🔸题目描述

总共有n个人在机房,每个人有一个标号(1<=标号<=n) ,他们分成了多个团队,需要你根据收到的m条消息判定指定的两个人是否在
一个团队中,具体的:
 
1、消息构成为abc,整数a、b分别代表两个人的标号,整数C代表指令
 
2、c = = 0 代表a和b在一个团队内
 
3、c == 1代表需要判定a和b的关系,如果a和b是一个团队,输出一行’we are a team’,如果不是, 输出一行 ‘we are not a team’
 
4、c为其他值,或当前行a或b超出1~n的范围,输出 ‘dapianzi’


🔸输入输出

输入
1、第一行包含两个整数n, m(1<=n,m<00000),分别表示有n个人和m条消息
2、随后的m行,每行一条消息,消息格式为: a b c(1<=a,b<=n,0<=C<=1)
 
输出
1、c ==1,根据a和b否在一个团队中输出一行字符串,在一个团队中输出we are a team’,不在一个团队中输出 ‘we are not a team’
2、c为其他值,或当前行a或b的标号于1或者大于n时,输出字符串 ‘dapianzi’
3、如果第一行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输出
We are a team
We are a team
We are a team
We are not a team

🔸样例2

输入
5 6
1 2 0
1 2 1
1 5 0
2 3 1
2 5 1
1 3 2输出
we are a team
we are not a team
we are a team
da pian zi

二、代码参考

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;class UnionFindSet {
public:vector<int> parent; // 将fa改为parent更符合语义UnionFindSet(int n) {parent.resize(n);for (int i = 0; i < n; i++) parent[i] = i;}int find(int x) {if (parent[x] != x) {return parent[x] = find(parent[x]);}return x;}void unionSet(int x, int y) {int x_parent = find(x);int y_parent = find(y);if (x_parent != y_parent) {parent[y_parent] = x_parent;}}
};int main() {int n, m;cin >> n >> m;if (n < 1 || n >= 100000 || m < 1 || m >= 100000) { // 先判断n和m是否在范围内cout << "Null" << endl;return 0;}vector<vector<int>> msgs(m, vector<int>(3));for (int i = 0; i < m; i++) {cin >> msgs[i][0] >> msgs[i][1] >> msgs[i][2];}UnionFindSet ufs(n + 1);sort(msgs.begin(), msgs.end(), [](vector<int>& x, vector<int>& y) { return x[2] < y[2]; });for (vector<int>& msg : msgs) {int a = msg[0], b = msg[1], c = msg[2];if (a < 1 || a > n || b < 1 || b > n) { // 判断a和b是否在范围内cout << "da pian zi" << endl;continue;}if (c == 0) {ufs.unionSet(a, b);}else if (c == 1) {cout << (ufs.find(a) == ufs.find(b) ? "We are a team" : "We are not a team") << endl;}else {cout << "da pian zi" << endl;}}return 0;
}

作者:KJ.JK

文章对你有所帮助的话,欢迎给个赞或者 star,你的支持是对作者最大的鼓励,不足之处可以在评论区多多指正,交流学习