我一直在尝试将解决方案提交给Kattis问题Almost Union Find,我的解决方案通过了第一个测试用例,但在第二个测试用例中它收到了运行时错误。我收到消息"退出信号11(SIGSEV)" ,意思是分割违规。但是,我不知道错误的原因是什么,并且我是c ++编程的新手,所以任何帮助都会非常感激。
我的计划:
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <unordered_set>
using namespace std;
typedef vector<int> vi;
unordered_set<int> seen(100000);
class UnionFind{
private: vi p, rank;
public:
UnionFind(int N){
p.assign(N,0);
rank.assign(N,0);
for(int i = 0; i < N; i++)
p[i] = i;
}
int findSet(int i){
return (p[i] == i) ? i : p[i] = findSet(p[i]);
}
bool isSameSet(int i, int j){
return findSet(i) == findSet(j);
}
void unionSet(int i, int j){
if(!isSameSet(i,j)){
int x = findSet(i), y = findSet(j);
if(rank[x] > rank[y]) p[y] = x;
else{
p[x] = y;
if(rank[x] == rank[y]) rank[y]++;
}
}
}
void moveSet(int i, int j){
if(!isSameSet(i,j)){
int x = findSet(j);
p[i] = x;
}
}
void printVals(int i){
int sum = 0;
int counter = 0;
for(auto itr = seen.begin(); itr != seen.end(); ++itr){
if(isSameSet(i,*itr)){
sum += *itr;
++counter;
}
}
printf("%d %d\n",counter,sum);
}
};
int main() {
int N, M;
while(scanf("%d %d",&N, &M) != EOF){
UnionFind uf(M);
for(int i = 0; i < M; i++){
int a,b,c;
scanf("%d %d",&a, &b);
//printf("a:%d b:%d c:%d\n",a,b,c);
if(a == 1){
scanf("%d",&c);
seen.insert(b);
seen.insert(c);
uf.unionSet(b,c);
}
else if(a == 2){
scanf("%d",&c);
seen.insert(b);
seen.insert(c);
uf.moveSet(b,c);
}
else if(a == 3){
uf.printVals(b);
}
}
seen.clear();
}
return 0;
}