classSolution { intpow(int x, int y){ if (y == 0) return1; else return x * pow(x, y - 1); } public: boolisArmstrong(int N){ constint number = N; vector<int> digits; while (N > 0) { digits.push_back(N % 10); N /= 10; } int s = 0; int power = digits.size(); for (auto digit : digits) { s += pow(digit, power); } return s == number; } };
classSolution { structUF { vector<int> parent; int count; UF(int n) { parent.resize(n); for (int i = 0; i < n; ++i) { parent[i] = i; } count = n; } // A utility function to find the subset of an element i intfind(int i) { if (parent[i] == i) return i; returnfind(parent[i]); }
// A utility function to do union of two subsets voidUnion(int x, int y) { int xset = find(x); int yset = find(y); if(xset != yset) { parent[xset] = yset; --count; } } }; public: intminimumCost(int N, vector<vector<int>>& conections){ UF uf(N); sort(conections.begin(), conections.end(), [](constauto& lhs, constauto&rhs) -> bool { return lhs[2] < rhs[2]; }); int ans = 0; for (constauto& edge : conections) { int a = edge[0] - 1, b = edge[1] - 1, cost = edge[2]; if (uf.find(a) != uf.find(b)) { uf.Union(a, b); ans += cost; if (uf.count == 1) return ans; } } return-1; } };