반응형

구간이 주어지면
reverse함수를 사용하여 뒤집고 출력해주면 되는 간단한 문제이다
인덱스 번호만 조금 신경써주어야 했던 문제이다
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int a=5,b=10;
for (int tmp=0; tmp < 10; tmp++)
{
cin >> a >> b;
reverse(arr+(a-1), arr+b);
}
for (int c : arr)
{
cout << c << " ";
}
return 0;
}
reverse(start, end);
reverse함수는 start부터 end-1까지의 인덱스를 뒤집기때문에 유의해주어야 한다.
// Authored by : BaaaaaaaaaaarkingDog
// Co-authored by : -
// http://boj.kr/4c29334a05624e9b88fde38677834a97
#include <bits/stdc++.h>
using namespace std;
int num[21];
int main(void){
ios::sync_with_stdio(0);
cin.tie(0);
for(int i = 1; i <= 20; i++) num[i] = i;
for(int i = 1; i <= 10; i++) {
int a, b;
cin >> a >> b;
reverse(num+a, num+b+1);
}
for(int i = 1; i <= 20; i++) cout << num[i] << ' ';
}
이 코드처럼 배열을 21칸 설정하고
0번이 아닌 1번인덱스부터 배열을 채워나가면
덜 헷갈리고 알아보기 쉬울 것 같다.
참고로
void reverse(int a, int b){
for(int i = 0; i < (b - a + 1) / 2; i++)
swap(num[a+i], num[b-i]);
}
reverse 함수를 선언해서 사용하는게 아닌
직접 구현해주는 방법이다
뒤집을 구간의 맨처음과 끝을 기준으로 swap하고
구간을 좁히면서 swap해주는 방식이다
반응형
'algorithm > 기초 코드' 카테고리의 다른 글
| [algorithm] 백준 2438번 별찍기 - 1 (0) | 2025.10.25 |
|---|---|
| [algorithm] 백준 15552번 빠른 A+B (0) | 2025.10.25 |
| [algorithm] 백준 1267번 핸드폰 요금 (0) | 2025.10.18 |
| [algorithm] 백준 2309번 일곱난쟁이 (0) | 2025.10.18 |
| [algorithm] 백준 2587번 대표값2 (0) | 2025.10.18 |
