본문 바로가기

Algorithm/BAEKJOON

[BOJ] 18429번 근손실(C++)

728x90
반응형

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

 

18429번: 근손실

웨이트 트레이닝을 좋아하는 어떤 대학원생은, 현재 3대 운동 중량 500의 괴력을 소유하고 있다. 다만, 하루가 지날 때마다 중량이 K만큼 감소한다. 예를 들어 K=4일 때, 3일이 지나면 중량이 488로

www.acmicpc.net

 

#include <iostream>
using namespace std;

int n, k;
int gain[8];
bool visited[8];
int weight = 500;
int answer = 0;

void dfs(int count){
	if(count == n) answer++;
	else{
		for(int i = 0; i < n; i++){
			if(!visited[i]){
				visited[i] = true;
				if(weight + gain[i] - k >= 500){
					weight += gain[i] - k;
					dfs(count + 1);
					weight -= gain[i] - k;
				}
				visited[i] = false;
			}
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	cin >> n >> k;
	for(int i = 0; i < n; i++){
		cin >> gain[i];
	}
	dfs(0);
	cout << answer;
	return 0;
}

 

이 문제를 next_permutation으로 풀 수 없는 이유

반례

3 4
4 4 4

정답: 6

출력: 1

next_permutation은 중복이 있는 원소의 경우 중복인 경우를 제외하고 순열을 만들어준다.

따라서 백트래킹으로 중복 순열을 구해서 해결했다.

728x90
반응형