zoukankan      html  css  js  c++  java
  • 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();
        }
    };
    
  • 相关阅读:
    POJ 2154
    POJ 1286
    Polycarp's problems
    Greedy Change
    Goods transportation
    Ugly Problem
    Happy Matt Friends
    Dense Subsequence
    Ray Tracing
    Batch Sort
  • 原文地址:https://www.cnblogs.com/pk28/p/9462393.html
Copyright © 2011-2022 走看看