在某城市里住着n个人,任何两个认识的人不是朋友就是敌人,而且满足: 我朋友的朋友是我的朋友; 我敌人的敌人是我的朋友; 我的敌人的朋友是我的敌人; 我的朋友的敌人是我的敌人; 所有是朋友的人组成一个团伙。告诉你关于这n个人的m 条信息,即某两个人是朋友,或者某两个人是敌人,请你编写一个程序,计算出这个城市最多可能有多少个团伙?直接给出c++代码
时间: 2024-03-27 09:35:43 浏览: 16
好的,以下是完整的C++代码实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
int find(int x, vector<int>& parent) {
if (parent[x] != x) {
parent[x] = find(parent[x], parent);
}
return parent[x];
}
void union_set(int x, int y, vector<int>& parent) {
int parent_x = find(x, parent);
int parent_y = find(y, parent);
if (parent_x != parent_y) {
parent[parent_x] = parent_y;
}
}
void merge_set(int x, int y, vector<int>& parent) {
int parent_x = find(x, parent);
int parent_y = find(y, parent);
if (parent_x != parent_y) {
parent[parent_x] = -parent_y;
parent[parent_y] = parent_x;
}
}
int main() {
int n, m;
cin >> n >> m;
vector<int> parent(n + 1);
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
for (int i = 0; i < m; i++) {
int op, x, y;
cin >> op >> x >> y;
if (op == 1) {
union_set(x, y, parent);
} else {
merge_set(x, y, parent);
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (parent[i] == i) {
ans++;
}
}
cout << ans << endl;
return 0;
}
```
和Python实现类似,我们也是用一个数组parent记录每个人所在的集合的代表元素,初始时每个人自成一个集合,即parent[i]=i。然后,对于每条朋友关系,我们将两个人所在的集合合并;对于每条敌人关系,我们需要将它们所在的集合标记为互相敌对。在合并集合时,我们还需要更新每个集合的代表元素的parent,具体实现和Python实现一样。
最后,我们遍历每个人的parent,统计一共有多少个代表元素,即有多少个团伙。
时间复杂度为O(m alpha(n)),其中alpha(n)是阿克曼函数的反函数,可以认为是一个很小的常数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)