https://www.acmicpc.net/problem/2920
코드 (C)
#include <stdio.h>
int main()
{
int arr[9], result;
for (int i = 0; i < 8; i++) scanf("%d", &arr[i]);
for (int i = 0; i < 7; i++)
{
if (arr[i]-arr[i+1] == 1) result = 0; // 감소
else if (arr[i+1]-arr[i] == 1) result = 1; // 증가
else
{
printf("mixed");
return 0;
}
}
if (result == 0) printf("descending");
else printf("ascending");
return 0;
}
코드 (C++)
#include <iostream>
using namespace std;
int main()
{
int arr[9], result;
for (int i = 0; i < 8; i++) cin >> arr[i];
for (int i = 0; i < 7; i++)
{
if (arr[i + 1] - arr[i] == 1) result = 1;
else if (arr[i] - arr[i + 1] == 1) result = 0;
else
{
cout << "mixed";
return 0;
}
}
if (result == 1) cout << "ascending";
else cout << "descending";
return 0;
}
코드설명
문제에서 설명하듯이 1부터 8까지 쭉 증가하면 ascending, 8부터 1까지 쭉 감소하면 descending을 출력하고, 둘 다 아닌 경우에는 mixed를 출력하면 된다.
먼저 배열을 이용해서 8개의 숫자를 입력받는다. 반복문을 0부터 7까지 도는데, 이때 arr[i]와 arr[i+1]을 비교할 것이므로 반복문을 8이 아닌 7까지 돈다. 만약 1씩 증가하면 result를 1로 정하고, 1씩 감소하면 result를 0으로 한다. 1씩 증가 혹은 감소를 하지 않는 경우에는 바로 mixed를 출력하고 프로그램을 종료한다.
반복문을 끝까지 도는 경우, result이 0이면 descending, 1이면 ascending을 출력하고 프로그램을 종료한다.
느낀 점
mixed를 출력하는 경우에는 그 뒤의 숫자들을 비교할 필요가 없기에 바로 프로그램을 종료하도록 코드를 작성했다. 무난하게 풀었다.
'PS (C, C++)' 카테고리의 다른 글
[백준/C & C++] 3009 네 번째 점 (0) | 2022.09.04 |
---|---|
[백준/C & C++] 5724 파인만 (0) | 2022.09.04 |
[백준/C & C++] 1297 TV 크기 (0) | 2022.09.03 |
[백준/C & C++] 7568 덩치 (0) | 2022.09.03 |
[백준/C & C++ ] 9020 골드바흐의 추측 (0) | 2022.08.29 |