From 0bf26392577a829d98e59074206a01ceb3d5ead7 Mon Sep 17 00:00:00 2001 From: Eatswap Date: Sat, 25 Mar 2023 16:18:16 +0800 Subject: [PATCH] add: 230325 --- cpp/2303/230325.cpp | 52 +++++++++++++++++++++++++++++++++++++++++ cpp/2303/CMakeLists.txt | 2 +- 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 cpp/2303/230325.cpp diff --git a/cpp/2303/230325.cpp b/cpp/2303/230325.cpp new file mode 100644 index 0000000..fab2193 --- /dev/null +++ b/cpp/2303/230325.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include + +class UnionFindSet { +private: + std::vector f; + +public: + explicit UnionFindSet(int n) : f(n + 1) { + std::iota(f.begin(), f.end(), 0); + } + + int find(int x) { + return (x == f[x]) ? x : (f[x] = find(f[x])); + } + + // Merge y to x + int uni(int x, int y) { + return f[find(y)] = find(x); + } +}; + +/** + * 2316. Count Unreachable Pairs of Nodes in an Undirected Graph + * + * You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. + * Return the number of pairs of different nodes that are unreachable from each other. + */ + +class Solution { +public: + static long long countPairs(int n, const std::vector>& edges) { + UnionFindSet ufs(n); + for (auto&& i : edges) + ufs.uni(i[0], i[1]); + std::unordered_map m; + for (int i = 0; i < n; ++i) + ++m[ufs.find(i)]; + long long ret = 0; + for (auto&& [_, cnt] : m) + ret += (long long)(n - cnt) * (long long)(cnt); + return ret >> 1; + } +}; + +int main() { + std::cout << Solution::countPairs(7, { + {0,2},{0,5},{2,4},{1,6},{5,4} + }); +} diff --git a/cpp/2303/CMakeLists.txt b/cpp/2303/CMakeLists.txt index 6155d9d..093ba78 100644 --- a/cpp/2303/CMakeLists.txt +++ b/cpp/2303/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2303) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2303 230324.cpp) +ADD_EXECUTABLE(2303 230325.cpp)