목차

적의 적

ps
링크acmicpc.net/…
출처BOJ
문제 번호12893
문제명적의 적
레벨골드 4
분류

이분 그래프

시간복잡도O(V+E)
인풋사이즈V<=2,000, E<=1,000,000
사용한 언어Python
제출기록103492KB / 1484ms
최고기록1456ms
해결날짜2022/11/07

풀이

코드

코드 1 - BFS (teflib)

"""Solution code for "BOJ 12893. 적의 적".

- Problem link: https://www.acmicpc.net/problem/12893
- Solution link: http://www.teferi.net/ps/problems/boj/12893

Tags: [Bipartite graph]
"""

import sys
from teflib import graph as tgraph


def main():
    N, M = [int(x) for x in sys.stdin.readline().split()]
    graph = [[] for _ in range(N)]
    for _ in range(M):
        A, B = [int(x) for x in sys.stdin.readline().split()]
        graph[A - 1].append(B - 1)
        graph[B - 1].append(A - 1)

    try:
        tgraph.two_coloring(graph)
    except ValueError:
        print('0')
    else:
        print('1')


if __name__ == '__main__':
    main()

코드 2 - Disjoint set

"""Solution code for "BOJ 12893. 적의 적".

- Problem link: https://www.acmicpc.net/problem/12893
- Solution link: http://www.teferi.net/ps/problems/boj/12893

Tags: [Bipartite graph]
"""


import sys
from teflib import disjointset


def main():
    N, M = [int(x) for x in sys.stdin.readline().split()]
    dsu = disjointset.DisjointSet(N * 2)
    for _ in range(M):
        A, B = [int(x) for x in sys.stdin.readline().split()]

        if dsu.find(A - 1) == dsu.find(B - 1):
            print('0')
            break
        dsu.union(A - 1, B - 1 + N)
        dsu.union(B - 1, A - 1 + N)
    else:
        print('1')


if __name__ == '__main__':
    main()