본문 바로가기
Study/Algorithm

[Algorithm-DFS] 최소차이

by Hoony-Daddy 2023. 8. 31.
728x90
/******************************************************************************

                              Online C++ Compiler.
               Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <stack>
int n, res = INT_MAX, can[2][21], ch[21];

void dfs(int l, int s){
    if(l == n/2){
        std::vector<int> b;
        std::vector<int> w;
        for(int i=0;i<n;i++){
            if(ch[i]==0){
                w.push_back(i);
            }
            else{
                b.push_back(i);
            }
        }
       
        int sum_b=0,sum_w=0;
        for(int i=0;i<b.size();i++){
            sum_w +=can[0][w[i]];
            sum_b +=can[1][b[i]];
        }
        res = std::min(res,std::abs(sum_b-sum_w));
    }
    else{
        for(int i=s;i<n;i++){
            ch[i]=1;
            dfs(l+1,i+1);
            ch[i]=0;
        }
    }
}

int main()
{
    // int n;
    std::cin >> n;
    // std::vector<int> blacks(n)
    // std::vector<int> whites(n)
    for(int i=0;i<n;i++){
        std::cin>>can[0][i]>>can[1][i];
    }
    dfs(0,0);
    std::cout<<res;
    return 0;
}