Notice
Recent Posts
Recent Comments
Link
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

dh-winternagi 님의 블로그

(11014) 컨닝 2 본문

백준 (C++)/Solve

(11014) 컨닝 2

dh-winternagi 2026. 4. 28. 01:26

https://www.acmicpc.net/problem/11014

단계별로 풀어보기

53단계(이분 매칭) 6번째

 

 

 

커닝 가능 범위를 보면 같은 행에 앉은 학생끼리는 절대 커닝이 불가능하고, 이웃한 행에 앉은 학생만 가능하다. 따라서 홀수 행과 짝수 행을 A그룹과 B그룹으로 나눌 수 있다. 교실의 책상 형태를 전부 탐색하며 A그룹과 B그룹에서 커닝이 가능한 경우 간선을 전부 만들어주고 이분 매칭 알고리즘을 쓰면 된다. 책상을 A, B그룹의 인덱스에 매칭하는 식을 짜는 것만 조심하면 된다.

 

 

 

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int solve(){
  int n, m, cnt= 0, res= 0;
  
  cin >> n >> m;
  
  int sz= (m+1)/2*n;
  
  vector seat(n+2, vector<bool> (m+2));
  vector<int> A(sz+1), B(sz+1), level(sz+1);
  vector<vector<int>> adj(sz+1);
  
  for(int i=1;i<=n;i++){
    string s;
    
    cin >> s;
    
    for(int j=1;j<=m;j++){
      if(s[j-1]=='.'){
        seat[i][j]= true;
        cnt++;
      }
    }
  }
  
  for(int i=1;i<=n;i++){
    for(int j=1;j<=m;j+=2){
      if(!seat[i][j])  continue;

      int z= j/2*n+i;
      if(seat[i-1][j-1])  adj[z].push_back(z-n-1);
      if(seat[i][j-1])  adj[z].push_back(z-n);
      if(seat[i+1][j-1])  adj[z].push_back(z-n+1);
      if(seat[i-1][j+1])  adj[z].push_back(z-1);
      if(seat[i][j+1])  adj[z].push_back(z);
      if(seat[i+1][j+1])  adj[z].push_back(z+1);
    }
  }
  
  auto leveling= [&](){
    queue<int> q;
    
    for(int i=1;i<=sz;i++){
      if(!A[i]){
        level[i]= 0;
        q.push(i);
      }else{
        level[i]= -1;
      }
    }
  
    while(!q.empty()){
      int now= q.front();
      q.pop();
  
      for(int next: adj[now]){
        if(B[next] && level[B[next]]==-1){
          level[B[next]]= level[now]+1;
          q.push(B[next]);
        }
      }
    }
  };
  
  auto matching= [&](auto self, int x) -> bool {
    int now= level[x];
    
    level[x]= -1;

    for(int y: adj[x]){
      if(!B[y] || (level[B[y]]==now+1&&self(self, B[y]))){
        A[x]= y;
        B[y]= x;
        return true;
      }
    }
  
    return false;
  };
  
  while(1){
    leveling();
    
    int flow= 0;
    
    for(int i=1;i<=sz;i++){
      if(!A[i]&&matching(matching, i))  flow++;
    }
    
    if(flow)  res+= flow;
    else  break;
  }
  
  return cnt-res;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  
  int T;
  
  cin >> T;
  
  while(T--){
    cout << solve() << "\n";
  }
  
  return 0;
}

'백준 (C++) > Solve' 카테고리의 다른 글

(11378) 열혈강호 4  (0) 2026.04.28
(17412) 도시 왕복하기 1  (0) 2026.04.28
(1867) 돌멩이 제거  (0) 2026.04.28
(1671) 상어의 저녁식사  (0) 2026.04.28
(1017) 소수 쌍  (0) 2026.04.28