38. Preprocessor Solution
[ 난이도: Easy | 분야: Other Concepts ]
1. 내용 정리
Preprocessor directive는 해쉬 문자(#)로 코드 안에서 구분되어 있는 줄이다.
이 줄들은 preprocessor를 지시한다.
preprocessor는 코드의 컴파일 시작 전에 실행되고 어느 코드든 regular statement에 의해 실제로 생성되기 이전에 모든 directive들을 제공한다.
#define INF 10000000
if(val == INF) {
// Do something
}
After the preprocessor has replaced the directives, the code will be
if(val == 10000000) { // Here INF is replaced by the value with which it's defined.
// Do something
}
또한 파라미터를 가진 함수 메크로를 생성할 수도 있다.
#define add(a,b) a + b
int x = add(a, b);
The second statement after the processor has replaced the directives will be:
int x = a + b;
2. 과제
과제 설명
당신은 오후에 학교에서 학생들에게 코드 짜는 법에 대해 가르치고 있다.
당신은 학생들에게 간단한 작업을 부여했다: 정수 배열에서의 최댓값과 최솟값의 차이를 구하시오.
수 시간 이후에, 학생들은 짠 코드를 가지고 왔다.
안타깝게도 각 코드들은 컴파일 되지 않았다! 당신은 학생들을 실망시키기 않기 위해, preprocessor macros를 추가하여 코드를 수정하지 않고도 작동하도록 하고 싶다.
에디터에서 잠겨 있는 stub 코드를 확인하고 코드가 잘 동작하도록 preprocessor macros를 추가해라.
입력 형식
첫 번째 줄은 배열의 크기를 나타내는 정수 N을 가지고 있다.
두 번째 줄은 공백으로 구분된 N개의 정수, x_1, x_2, ..., x_n을 가지고 있고 이는 배열의 원소다.
제약 사항
N은 1보다 크거나 같고 10^3보다 작거나 같다.
x_i는 -10^8보다 크거나 같고 10^8보다 작거나 같다.
출력 형식
stdout을 이용하여 출력할 필요가 없다. 필요한 preprocessor macros를 작성한다면, 에디터의 잠긴 코드에는 Result = Z를 출력하고 Z는 배열에서의 최댓값과 최솟값의 차이이다.
입력 예시
5
32 332 -23 -154 65
출력 예시
Result = 486
설명
332-(-154) = 486
문제
/* Enter your macros here */
#include <iostream>
#include <vector>
using namespace std;
#if !defined toStr || !defined io || !defined FUNCTION || !defined INF
#error Missing preprocessor definitions
#endif
FUNCTION(minimum, <)
FUNCTION(maximum, >)
int main(){
int n; cin >> n;
vector<int> v(n);
foreach(v, i) {
io(v)[i];
}
int mn = INF;
int mx = -INF;
foreach(v, i) {
minimum(mn, v[i]);
maximum(mx, v[i]);
}
int ans = mx - mn;
cout << toStr(Result =) <<' '<< ans;
return 0;
}
정답
/* Enter your macros here */
#define INF (unsigned)!((int)0)
#define FUNCTION(name, operator) inline void name(int ¤t, int candidate) {!(current operator candidate) ? current = candidate : false;}
#define io(v) cin>>v
#define toStr(str) #str
#define foreach(v, i) for (int i = 0; i < v.size(); ++i)
#include <iostream>
#include <vector>
using namespace std;
#if !defined toStr || !defined io || !defined FUNCTION || !defined INF
#error Missing preprocessor definitions
#endif
FUNCTION(minimum, <)
FUNCTION(maximum, >)
int main(){
int n; cin >> n;
vector<int> v(n);
foreach(v, i) {
io(v)[i];
}
int mn = INF;
int mx = -INF;
foreach(v, i) {
minimum(mn, v[i]);
maximum(mx, v[i]);
}
int ans = mx - mn;
cout << toStr(Result =) <<' '<< ans;
return 0;
}
©️Hackerrank. All Rights Reserved.
'프로그래밍 언어 > C, C++' 카테고리의 다른 글
[Hackerrank] 39. Operator Overloading (0) | 2024.03.02 |
---|---|
[Hackerrank] 12. Attribute Parser (0) | 2024.03.01 |
[Hackerrank] 37. C++ Class Templates (0) | 2024.03.01 |
[Hackerrank] 36. Magic Spells (3) | 2024.02.29 |
[Hackerrank] 35. Accessing Inherited Functions (0) | 2024.02.27 |