알고리즘 모음(C++)

백준 9576 - 책 나눠주기(C++) 본문

백준

백준 9576 - 책 나눠주기(C++)

공대생의 잡다한 사전 2023. 2. 11. 20:27

문제 링크입니다. https://www.acmicpc.net/problem/9576

 

9576번: 책 나눠주기

백준이는 방 청소를 하면서 필요 없는 전공 서적을 사람들에게 나눠주려고 한다. 나눠줄 책을 모아보니 총 N권이었다. 책이 너무 많기 때문에 백준이는 책을 구분하기 위해 각각 1부터 N까지의

www.acmicpc.net

이분 매칭을 이용해 푸는 문제입니다.

 

 

자세한 것은 코드를 참고해주세요

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstdio>
#include <string>
#include <deque>
#include <stack>
#include <map>
#define LL long long
#define pp pair<int, int>
#define F first
#define S second

using namespace std;

int test_case;
int N, M;
vector<int> Match[1011];
vector<int> a_match, b_match;
bool check[1011];

bool dfs(int start){
    if(check[start]) return false;
    check[start] = true;
    for(int i = 0; i < Match[start].size(); i++){
        int x = Match[start][i];
        if(b_match[x] == -1 || dfs(b_match[x])){
            a_match[start] = x;
            b_match[x] = start;
            return true;
        }
    }
    return false;
}

void solve(){
    a_match = vector<int>(M+1, -1);
    b_match = vector<int>(N+1, -1);
    int size = 0;
    for(int i = 1; i <= M; i++){
        memset(check, false, sizeof(check));
        if(dfs(i)) size++;
    }
    cout << size << "\n";
}

int main() {
    cin.tie(0);
	cout.tie(0);
	cin >> test_case;
	for(int t = 1; t <= test_case; t++){
	    memset(Match, 0, sizeof(Match));
	    a_match.clear();
	    b_match.clear();
	    cin >> N >> M;
	    for(int i = 1; i <= M; i++){
	        int x, y;
	        cin >> x >> y;
	        for(int j = x; j <= y; j++){
	            Match[i].push_back(j);
	        }
	    }
	    solve();
	}
	return 0;
}

 

 

질문 및 조언은 댓글을 남겨주세요