【科学刷题】并查集
作者:互联网
微软10-28下午的二面考了并查集,没写出来,羞耻
今天写3道题,省份的数量,冗余连接,打砖块
class UnionSet{
private:
int cnt;
vector<int> parent;
public:
UnionSet(int n):cnt(n){
for(int i=0;i<n;++i) parent.emplace_back(i);
}
int find(int x){
if(parent[x]!=x)
parent[x] = find(parent[x]);
return parent[x];
}
void union_two(int a, int b){
int pa = find(a);
int pb = find(b);
if(pa == pb)
return;
cnt--;
parent[pa] = pb;
}
int get_cnt(){return cnt;}
};
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
UnionSet us=n;
for(int i=0;i<n;++i)for(int j=i+1;j<n;++j)if(isConnected[i][j])us.union_two(i,j);
return us.get_cnt();
}
};
标签:cnt,parent,int,查集,UnionSet,科学,find,刷题 来源: https://blog.csdn.net/TQCAI666/article/details/121070316