leetcode 890. Possible Bipartition
Posted いいえ敗者
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 890. Possible Bipartition相关的知识,希望对你有一定的参考价值。
Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size.
Each person may dislike some other people, and they should not go into the same group.
Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.
Return true if and only if it is possible to split everyone into two groups in this way.
Example 1:
Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Explanation: group1 [1,4], group2 [2,3]
Example 2:
Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false
Example 3:
Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
Output: false
Note:
1 <= N <= 2000
0 <= dislikes.length <= 10000
1 <= dislikes[i][j] <= N
dislikes[i][0] < dislikes[i][1]
There does not exist i != j for which dislikes[i] == dislikes[j].
思路:二分图染色
class Solution {
public:
vector<int>G[2100];
int color[2100];
//memset(color, -1, sizeof (color));
int bfs() {
queue<int>q;
q.push(1);
color[1] = 1;
while(!q.empty()) {
int v1 = q.front();
q.pop();
for(int i = 0; i < G[v1].size(); i++) {
int v2 = G[v1][i];
if(color[v2] == -1) {
color[v2] = -color[v1];
q.push(v2);
}
else if(color[v1] == color[v2])
return 0;
}
}
return 1;
}
bool possibleBipartition(int N, vector<vector<int>>& dislikes) {
for (int i = 0; i < dislikes.size(); ++i) {
vector<int> x = dislikes[i];
//cout << x[0] << " " <<x[1] << endl;
G[x[0]].push_back(x[1]);
G[x[1]].push_back(x[0]);
}
for (int i = 0; i <= 2000; ++i)color[i] = -1;
return bfs();
}
};
以上是关于leetcode 890. Possible Bipartition的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 890. Find and Replace Pattern
算法leetcode890. 查找和替换模式(rust和go的性能是真的好)
算法leetcode890. 查找和替换模式(rust和go的性能是真的好)