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();
        }
    };
    
  • 相关阅读:
    CentOS 6.x Radius
    Linux系统优化
    Linux 常用检测命令
    Linux 修改终端命令提示符颜色
    Linux LVM简明教程
    剑指Offer 通过中序和先序遍历重建二叉树
    剑指Offer 树的子结构
    剑指Offer 从上往下打印二叉树(dfs)
    剑指Offer 把字符串转换成整数
    剑指Offer 两个链表的第一个公共结点
  • 原文地址:https://www.cnblogs.com/pk28/p/9462393.html
Copyright © 2011-2022 走看看