본문 바로가기
알고리즘 문제풀이/SWEA

[SWEA 4012] 요리사(C++)

by 소보루:-) 2020. 3. 16.

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWIeUtVakTMDFAVH

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

#include <iostream>
#include <cstring>
#include <vector>
#include <cmath>
#include <cstdio>
using namespace std;

int N;
int map[16][16];
bool chk[16];
int ans;


void Solve(int index, int cnt) {
	if (cnt == N / 2) {
		//계산
		vector<int> vectorA, vectorB;
		int A = 0, B = 0;
		for (int i = 0; i < N; i++) {
			if (chk[i] == 1) vectorA.push_back(i);
			else if(chk[i] == 0) vectorB.push_back(i);
		}
		
		for (int i = 0; i < vectorA.size() - 1; i++) {
			for (int j = i + 1; j < vectorA.size(); j++) {
				A += map[vectorA[i]][vectorA[j]] + map[vectorA[j]][vectorA[i]];
				B += map[vectorB[i]][vectorB[j]] + map[vectorB[j]][vectorB[i]];
			}
		}
		if (ans > abs(A - B))ans = abs(A - B);
		
		return;
	}
	for (int i = index; i < N; i++) {
		if (chk[i] == 0) {
			chk[i] = 1;
			Solve(i, cnt+1);
			chk[i] = 0;
		}
	}

}
int main() {
	//freopen("input.txt", "r", stdin);
	int T;
	cin >> T;
	for (int tc = 1; tc <= T; tc++) {
		memset(chk, 0, sizeof(chk));
		ans = 987654321;
		cin >> N;
		//cout << N;
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				cin >> map[i][j];
			}
		}
		
		Solve(1, 0);

		cout << "#" << tc << " " << ans << '\n';
	}

	return 0;
}

댓글