-
[ 2920 ] 음계 - array, vector알고리즘/BOJ 2021. 7. 27. 13:42
< array, vector > - < solve등급 >
[ 2920 ]
음계
다장조는 c d e f g a b C, 총 8개 음으로 이루어져있다. 이 문제에서 8개 음은 다음과 같이 숫자로 바꾸어 표현한다. c는 1로, d는 2로, ..., C를 8로 바꾼다.
1부터 8까지 차례대로 연주한다면 ascending, 8부터 1까지 차례대로 연주한다면 descending, 둘 다 아니라면 mixed 이다.
연주한 순서가 주어졌을 때, 이것이 ascending인지, descending인지, 아니면 mixed인지 판별하는 프로그램을 작성하시오.
:: 입력
첫째 줄에 8개 숫자가 주어진다. 이 숫자는 문제 설명에서 설명한 음이며, 1부터 8까지 숫자가 한 번씩 등장한다.
:: 출력
첫째 줄에 ascending, descending, mixed 중 하나를 출력한다.
- try 1
: 처음에는 1씩 차이나는지 확인하고 아닌 경우 mixed 를 체크하는 코드를 짰는데
그러면 ascending 인지 descending인지 구분 할 수가 없기 때문에 오름차순 배열과 내림차순 배열을 미리 만들어두고 비교했음
근데 연산이 쓸데 없이 너무 많아서 맘에 안들었는데
틀렸음
try1 코드
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define endl "\n" int main() { int as[8] = { 1,2,3,4,5,6,7,8 }; int des[8] = { 8,7,6,5,4,3,2,1 }; int input[8]; bool isAs = true; bool isDes = true; bool isMix = false; for (int i = 0; i < 8; i++) { cin >> input[i]; if (as[i] != input[i]) { isAs = false; } else if (des[i] != input[i]) { isDes = false; } } if (isAs == false && isDes == false) { isMix = true; } if (isAs) { cout << "ascending"; } else if (isDes) { cout << "descending"; } else if (isMix) { cout << "mixed"; } }
아이디어
입력받은 숫자가 순차적으로 증가하는 인덱스와 같은 경우 카운트를 늘리고
인덱스와 더해서 9가 될 때 카운트를 줄임
입력을 다 받은 후
그 카운트수가 8이 된 경우 오름차순이고
카운트수가 -8이 된 경우 내림차순
그렇지 않은 경우 mixed 를 출력
- try 2
: 하나씩 비교하는 방법은 너무 비효율적인 거 같아서
그냥 각 원소의 차이가 1이 아닌 경우 mixed 를 체크하고
배열을 한 바퀴 다 돌았을 때 mixed가 아니라면 원소의 차이가 +1 인지 -1인지 확인해서 출력함
훨씬 깔끔해졌고 맞았음 ㅎㅎ
정답 코드
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define endl "\n" int main() { int nums[8]; bool isMixed = false; for (int i = 0; i < 8; i++) { cin >> nums[i]; } for (int i = 0; i < 7; i++) { if (abs(nums[i] - nums[i + 1]) != 1) { isMixed = true; break; } } if (isMixed) { cout << "mixed" << endl; } else if (nums[0] - nums[1] > 0) { cout << "descending" << endl; } else cout << "ascending" << endl; }
정답 코드
#include<stdio.h> #include<string.h> int main() { char str[100]={0}; scanf("%[^\n]s",str); if(strcmp(str,"1 2 3 4 5 6 7 8")==0) printf("ascending"); else if(strcmp(str,"8 7 6 5 4 3 2 1")==0)printf("descending"); else printf("mixed"); }
아예 입력 한 줄을 문자열로 받아서 비교한 답안도 있었음
정답 코드
#include <stdio.h> int main() { int i, a = 0, n; for(i = 1; i <= 8; i++){ scanf("%d", &n); if(n==i){ a++; } else if(n + i == 9){ a--; } } if(a==8){ printf("ascending"); } else if(a==-8){ printf("descending"); } else{ printf("mixed"); } }
'알고리즘 > BOJ' 카테고리의 다른 글
[ 5597 ] 과제 안 내신 분 ..? - array, vector (0) 2021.07.27 [ 2953 ] 나는 요리사다 - array, vector (0) 2021.07.27 [ 11328 ] Strfry - array, vector (0) 2021.07.26 [ 1919 ] 에너그램 만들기 - array, vector (0) 2021.07.26 [ 10808 ] 알파벳 개수 - array, vector (0) 2021.07.26