分析:
人名字符串用map映射一下就可以了,这个是一个存储int的并查集,有优化。
代码:
#include <iostream>
#include <vector>
#include <map>
using namespace std
;
class UnionFindSets
{
public:
UnionFindSets();
UnionFindSets(int n
);
void link(int x
, int y
);
bool isLink(int x
, int y
);
private:
vector
<int>fa
;
};
UnionFindSets
::UnionFindSets() {
fa
.clear();
}
UnionFindSets
::UnionFindSets(int n
) {
fa
.clear();
for (int i
= 0; i
<= n
; i
++) {
fa
.push_back(i
);
}
}
void UnionFindSets
::link(int x
, int y
) {
while (x
!= fa
[x
]) {
fa
[x
] = fa
[fa
[x
]];
x
= fa
[x
];
}
while (y
!= fa
[y
]) {
fa
[y
] = fa
[fa
[y
]];
y
= fa
[y
];
}
fa
[x
] = y
;
}
bool UnionFindSets
::isLink(int x
, int y
) {
while (x
!= fa
[x
]) {
fa
[x
] = fa
[fa
[x
]];
x
= fa
[x
];
}
while (y
!= fa
[y
]) {
fa
[y
] = fa
[fa
[y
]];
y
= fa
[y
];
}
return x
== y
;
}
map
<string
, int>mp
;
int main()
{
int T
, n
= 0;
cin
>> T
;
UnionFindSets ans
= UnionFindSets(2e5 + 10);
while (T
--) {
int op
;
string a
, b
;
cin
>> op
>> a
>> b
;
if (op
== 0) {
if (mp
.count(a
) == 0) {
mp
[a
] = n
++;
}
if (mp
.count(b
) == 0) {
mp
[b
] = n
++;
}
ans
.link(mp
[a
], mp
[b
]);
}
else {
if (mp
.count(a
) == 0) {
mp
[a
] = n
++;
}
if (mp
.count(b
) == 0) {
mp
[b
] = n
++;
}
if (ans
.isLink(mp
[a
], mp
[b
]) == true) {
cout
<< "yes" << endl
;
}
else {
cout
<< "no" << endl
;
}
}
}
}
转载请注明原文地址: https://mac.8miu.com/read-514804.html