선택은 나의 것

[BOJ 백준] 1867번 돌멩이 제거 본문

☽ Algorithm/BOJ

[BOJ 백준] 1867번 돌멩이 제거

Algoribi 2021. 7. 23. 09:33

문제

BOJ number : https://www.acmicpc.net/problem/1867

 

1867번: 돌멩이 제거

첫째 줄에 n과 k가 주어진다. (1 ≤ n ≤ 500, 1 ≤ k ≤ 10,000) 이후 k개의 줄에는 돌멩이의 위치가 한 줄에 하나씩 주어진다. 줄마다 첫 번째 숫자는 행 번호, 두 번째 숫자는 열 번호를 나타낸다.

www.acmicpc.net

접근

이분 매칭(Bipartite Matching)을 이용하여 문제를 해결하였다.

코드

#include <iostream>
#include <vector>

using namespace std;

int n, k, ans = 0, visit[510], matchNum[510] = {0};
vector<int> graph[510];

int dfs(int n){
    for (int i : graph[n]) {
        if (!visit[i]) {
            visit[i] = 1;
            if (!matchNum[i] || dfs(matchNum[i])) {
                matchNum[i] = n;
                return 1;
            }
        }
    }
    return 0;
}

int main() {
    cin >> n >> k;

    for (int i = 0; i < k; i++) {
        int a, b;
        cin >> a >> b;
        graph[a].push_back(b);
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) 
            visit[j] = 0;
        ans += dfs(i);
    }
    
    cout << ans;

    return 0;
}

 

깃 허브 주소 : https://github.com/algoribi/algorithm-study

'☽ Algorithm > BOJ' 카테고리의 다른 글

[BOJ 백준] 1865번 웜홀  (0) 2021.07.25
[BOJ 백준] 2671번 잠수함식별  (0) 2021.07.24
[BOJ 백준] 11375번 열혈강호  (0) 2021.07.22
[BOJ 백준] 14426번 접두사 찾기  (0) 2021.07.16
[BOJ 백준] 1701번 Cubeditor  (0) 2021.07.15
Comments