문제

https://www.acmicpc.net/problem/10819
10819번: 차이를 최대로
첫째 줄에 N (3 ≤ N ≤ 8)이 주어진다. 둘째 줄에는 배열 A에 들어있는 정수가 주어진다. 배열에 들어있는 정수는 -100보다 크거나 같고, 100보다 작거나 같다.
www.acmicpc.net
코드
#include <iostream>
using namespace std;
int arr[8];
int arr2[8];
int isVisited[8];
int n;
int maxValue = -1;
void dfs(int cnt){
if(cnt==n){
int result = 0;
for(int i=0; i<n-1; i++){
result += abs(arr2[i+1]-arr2[i]);
}
if(result>maxValue) maxValue = result;
return;
}
for(int i=0; i<n; i++){
if(!isVisited[i]){
isVisited[i] = true;
arr2[cnt] = arr[i];
dfs(cnt+1);
isVisited[i] = false;
}
}
}
int main(){
cin >> n;
for(int i=0; i<n; i++){
cin >> arr[i];
}
dfs(0);
cout << maxValue;
return 0;
}
정리
https://kdongree.tistory.com/84 이 문제와 매우 유사한 문제이다. 전형적인 백트래킹 패턴 문제인 것 같다.
참조
'Beakjoon > backtracking' 카테고리의 다른 글
| [백준] 6603번 로또 (C++) - backtracking (0) | 2022.05.07 |
|---|---|
| [백준] 18290번 NM과 K (1) (C++) - backtracking (0) | 2022.04.26 |
| [백준] 15657번 N과 M (8) (C++) - backtracking (0) | 2022.04.15 |
| [백준] 15656번 N과 M (7) (C++) - backtracking (0) | 2022.04.15 |
| [백준] 15655번 N과 M (6) (C++) - backtracking (0) | 2022.04.15 |