#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
unordered_map<int, int> unionFindSet;
int myFind(int x)
{
if (unionFindSet[x] < 0)
return x;
return unionFindSet[x] = myFind(unionFindSet[x]);
}
void Union(int root1, int root2)
{
root1 = myFind(root1);
root2 = myFind(root2);
if (unionFindSet[root1] > unionFindSet[root2])
{
unionFindSet[root2] += unionFindSet[root1];
unionFindSet[root1] = root2;
}
else
{
unionFindSet[root1] += unionFindSet[root2];
unionFindSet[root2] = root1;
}
}
void inputConnection()
{
int start, end;
cin >> start >> end;
unionFindSet[start] = end;
int root1 = myFind(start);
int root2 = myFind(end);
if (root1 != root2)
Union(root1, root2);
}
void checkConnection()
{
int start, end;
cin >> start >> end;
int root1 = myFind(start);
int root2 = myFind(end);
if (root1 != root2)
cout << "no" << endl;
else
cout << "yes" << endl;
}
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
unionFindSet[i] = -1;
}
char operation;
while (1)
{
cin >> operation;
if (operation == 'S')
break;
if (operation == 'I')
{
inputConnection();
}
else if (operation == 'C')
{
checkConnection();
}
}
int sum = 0;
for (auto& it : unionFindSet)
{
if (it.second == -1)
sum++;
}
if (sum == 1)
{
cout << "The network is connected." << endl;
}
else
{
printf("There are %d components.\n", sum);
}
}
File Transfer 并查集
最新推荐文章于 2024-07-25 11:27:31 发布