[기억할 내용들]
- 나는 배열의 값을 반복문 돌 때마다 ++ 해주고 반복문이 끝나면 비로소 배열에 0인 값이 없으면 YES 를 출력하는 식으로 풀었다.
- 이 문제에서는 배열의 값이 0이 아닌게 있거나, 인덱스가 벡터 크기를 벗어나면 NO 를 출력하는 식으로 푸는 게 더 간결한 풀이 방법이었다.
- 반복문 속 if 조건문에서 int(pre-now) 의 값이 벡터 범위를 벗어나는지를 판별하는 조건이 벡터 요소의 값이 1인지 아닌지를 판별하는 조건보다 더 먼저 나와야 한다.
[나의 코드]
- 반복문이 끝나고 나서야 비로소 결과값을 결정하는 풀이 방식
#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
// [0]: 1, [1]: 2, ... [n-2]: n-1
vector<int> table(n-1);
int prev;
cin >> prev;
for (int i = 1; i < n; i++) {
int tmp;
cin >> tmp;
if (abs(tmp - prev) - 1 > table.size())
continue;
table[abs(tmp-prev)-1]++;
prev = tmp;
}
bool flag = true;
for (int i = 0; i < table.size(); i++) {
if (table[i] == 0) {
flag = false;
break;
}
}
if (flag)
cout << "YES\n";
else
cout << "NO\n";
return 0;
}
- 미리 조건문으로 판별해서 만족 하지 않으면 NO 출력하고 끝내는 방식
#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
vector<int> table(n);
int prev;
int now;
bool flag = true;
cin >> prev;
for (int i = 1; i < n; i++) {
cin >> now;
if (abs(now - prev) - 1 > table.size() || table[abs(now - prev)] != 0) {
flag = false;
break;
}
table[abs(now - prev)]++;
}
if (flag)
cout << "YES\n";
else
cout << "NO\n";
return 0;
}
[강의 코드]
#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, i, now, pre, pos;
scanf_s("%d", &n);
vector<int> ch(n);
scanf_s("%d", &pre);
for (i = 1; i < n; i++) {
scanf_s("%d", &now);
pos = abs(pre - now);
if (pos > 0 && pos < n && ch[pos] == 0) ch[pos] = 1;
else {
printf("NO\n");
return 0;
}
pre = now;
}
printf("YES\n");
return 0;
}
[의견]
반복문 속 if 조건문에서 int(pre-now) 의 값이 벡터 범위를 벗어나는지를 판별하는 조건이 벡터 요소의 값이 1인지 아닌지를 판별하는 조건보다 더 먼저 나와야 한다. 이렇게 하지 않으면 벡터 요소에 접근할 때 범위를 벗어나는 에러가 발생할 가능성이 있기 때문이다. 이번 풀이에서는 강의 코드랑 핵심적인 부분이 같아서 기분이 좋다.