diff options
author | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
commit | 7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch) | |
tree | eb7a24ee2067f92245c57bb118e85a1baf15df50 /other/possible_bipartition.cpp | |
parent | 5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff) | |
download | leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip |
chore: move cpp and rust code to directory
Diffstat (limited to 'other/possible_bipartition.cpp')
-rw-r--r-- | other/possible_bipartition.cpp | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/other/possible_bipartition.cpp b/other/possible_bipartition.cpp new file mode 100644 index 0000000..6dd4175 --- /dev/null +++ b/other/possible_bipartition.cpp @@ -0,0 +1,45 @@ +#include "leetcode.h" + +class Solution { +public: + bool possibleBipartition(int n, vvd & dislikes) { + enum color { green = -1, uncolored, blue }; + if (n == 1 || dislikes.size() == 0) + return true; + unordered_map<int, vector<int>> dislikeTable; + unordered_map<int, int> colorTable; + function<bool(int, int)> helper; + helper = [&](int personID, int color) -> bool { + colorTable[personID] = color; + for (const int &other : dislikeTable[personID]) { + if (colorTable[other] == color) + return false; + if (colorTable[other] == uncolored && (!helper(other, -color))) + return false; + } + return true; + }; + for (const auto &relation : dislikes) { + int p1 = relation[0], p2 = relation[1]; + dislikeTable[p1].emplace_back(p2); + dislikeTable[p2].emplace_back(p1); + } + for (int i = 1; i <= n; i++) + if (colorTable[i] == uncolored && (!helper(i, blue))) + return false; + return true; + } +}; + +int main() { + Solution obj; + vvd dislikes1 = {{1, 2}, {1, 3}, {2, 4}}, + dislikes2 = {{1, 2}, {1, 3}, {2, 3}}, + dislikes3 = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {1, 5}}; + testBool(obj.possibleBipartition(4, dislikes1)); + // true: [2,3] [1,4] + testBool(obj.possibleBipartition(3, dislikes2)); + // false + testBool(obj.possibleBipartition(5, dislikes3)); + // false +} |