LeetCode·每日一题·886.可能的二分法·并查集

题目LeetCode·每日一题·886.可能的二分法·并查集_第1张图片

 

示例LeetCode·每日一题·886.可能的二分法·并查集_第2张图片

 

思路

同样我们也可以用「并查集」来进行分组判断:由于最后只有两组,所以某一个人全部不喜欢人一定会在同一个组中,我们可以用「并查集」进行连接,并判断这个人是否与他不喜欢的人相连,如果相连则表示存在冲突,否则说明此人和他不喜欢的人在当前可以进行合法分组。

代码


int findFa(int x, int* fa) {
    return fa[x] < 0 ? x : (fa[x] = findFa(fa[x], fa));
}

void swap(int *a, int *b) {
    int c = *a;
    *a = *b;
    *b = c;
}

void unit(int x, int y, int* fa) {
    x = findFa(x, fa);
    y = findFa(y, fa);
    if (x == y) {
        return ;
    }
    if (fa[x] < fa[y]) {
        swap(&x, &y);
    }
    fa[x] += fa[y];
    fa[y] = x;
}

bool isconnect(int x, int y, int* fa) {
    x = findFa(x, fa);
    y = findFa(y, fa);
    return x == y;
}

bool possibleBipartition(int n, int** dislikes, int dislikesSize, int* dislikesColSize) {
    int color[n + 1], fa[n + 1];
    struct ListNode *g[n + 1];
    for (int i = 0; i <= n; i++) {
        color[i] = 0, fa[i] = -1;
        g[i] = NULL;
    }
    for (int i = 0; i < dislikesSize; i++) {
        int a = dislikes[i][0], b = dislikes[i][1];
        struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
        node->val = a;
        node->next = g[b];
        g[b] = node;
        node = (struct ListNode *)malloc(sizeof(struct ListNode));
        node->val = b;
        node->next = g[a];
        g[a] = node;
    }
    for (int i = 1; i <= n; ++i) {
        for (struct ListNode *node = g[i]; node; node = node->next) {
            unit(g[i]->val, node->val, fa);
            if (isconnect(i, node->val, fa)) {
                for (int j = 0; j <= n; j++) {
                    struct ListNode * node = g[j];
                    while (node) {
                        struct ListNode * prev = node;
                        node = node->next;
                        free(prev);
                    }
                }
                return false;
            }
        }
    }
    for (int j = 0; j <= n; j++) {
        struct ListNode * node = g[j];
        while (node) {
            struct ListNode * prev = node;
            node = node->next;
            free(prev);
        }
    }
    return true;
}


作者:小迅
链接:https://leetcode.cn/problems/possible-bipartition/solutions/1896081/bing-cha-ji-zhu-shi-chao-ji-xiang-xi-by-f50yf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(LeetCode刷题笔记,leetcode,算法,职场和发展)