用的并查集,大家凑合看看,等大佬来完善
C++ 代码
const int MAXN = 50005;
int f[MAXN];
int fid(int x){
if(f[x] != x){
x = fid(f[x]);
}
return f[x];
}
void uni(int x, int y){
x = fid(x);
y = fid(y);
if(x != y){
f[x] = y;
}
}
class Solution {
public:
int minReorder(int n, vector<vector<int>>& conn) {
for(int i = 0; i < n; i++){
f[i] = i;
}
int ans = 0;
for(int i = 0; i < conn.size(); i++){
if(fid(conn[i][0]) == 0){
ans++;
swap(conn[i][0], conn[i][1]);
}
uni(conn[i][0], conn[i][1]);
}
return ans;
}
};