알고리즘 문제/BOJ
10819번 차이를 최대로
parkit
2018. 11. 29. 21:58
728x90
반응형
https://www.acmicpc.net/problem/10819
자꾸 틀렸다고 나와서 어디가 틀렸는지 계속 봤다.
알고보니, Swap(i, i + 1);로 계속 써서 틀렸던 것이었다.
즉, 옆의 자리하고만 바꾸고 있었다.
Swap(pos, i); 이렇게 작성해야 옆의 자리가 아닌 그 넘어 자리가 모두 바꿀 수 있다.
참고로,
if(pos == N-1)이라고 해서,
[0]와 [N-1]이 교환이 안 되는 것은 아니다.
for문에 의해 pos가 0이고, i가 N - 1가 되는 경우가 있기 때문이다.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | #include <iostream> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> #include <map> using namespace std; vector<int> v; int N = 0; int MAX = -101; void Swap(int i, int j) { int temp = v.at(i); v.at(i) = v.at(j); v.at(j) = temp; } int calc() { int ret = 0; for (int i = 0; i < N - 1; i++) { ret += abs(v.at(i) - v.at(i + 1)); } return ret; } void BackTracking(int pos) { if (pos == N - 1) { MAX = max(MAX, calc()); return; } for (int i = pos; i < N; i++) { Swap(pos, i); BackTracking(pos + 1); Swap(pos, i); } /* // 실수했던 코드 for(int i = 0; i < N; i++) { Swap(i, i + 1); BackTracking(v, pos + 1); Swap(i, i + 1); } */ } int main() { int n = 0; MAX = -101; scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%d", &n); v.push_back(n); } BackTracking(0); printf("%d\n", MAX); return 0; } | cs |
728x90
반응형