# Hall's Marriage Theorem Simulation
'''
참고자료
[1] https://[Log in to view URL]
[2] 알고리즘 문제해결 전략 2 
'''
n=int(input("전체 남성의 수를 입력하세요.(예. 1, 2, 3...) : "))
print("i번째 남성이 알고 있는 여성의 번호를 i번째 줄에 공백으로 구분지어 입력하세요.")
print("(예. 1번 남성이 알고 있는 여성의 번호가 2와 3일 경우, 2 3을 입력)")

adj = [[] for _ in range(n+1)]
tot_set = set() # 전체 여성 집합

for i in range(1, n+1) :
    s = list(map(int, input().split()))
    tot_set = tot_set|set(s)

    for j in s :
        adj[i].append(j)

m = len(tot_set) # 전체 남성이 알고 있는 여성의 수
mMatch = [-1 for _ in range(n+1)]
wMatch = {}
visited = [False for _ in range(n+1)]

def dfs(start) :
    if visited[start] :
        return False
    visited[start]=True

    for w in adj[start] :
        if w not in wMatch or dfs(wMatch[w]) :
            mMatch[start]=w
            wMatch[w]=start
            return True
                
    return False

if n>m:
    print("결혼 매칭을 성사시킬 수 없습니다.")
else :
    matching = 0
    for start in range(1, n+1) :
        visited = [0 for _ in range(n+1)]
        if dfs(start) :
            matching += 1

    if matching == n :
        print("결혼 매칭을 성사시킬 수 있습니다.")
        for i in range(1, len(mMatch)) :
            print(i, mMatch[i])
    else :
        print("결혼 매칭을 성사시킬 수 없습니다.")

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: