백준 17298번(by C++)
문제
코드
시간 초과(이중 반복문)
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; i++) {
int t;
cin >> t;
v.push_back(t);
}
for (int i = 0; i < n; i++) {
int j = i;
bool check = false;
while (j < n) {
if (v[i] < v[j]) {
cout << v[j] << ' ';
check = true;
break;
}
j++;
}
if (!check)
cout << -1 << ' ';
}
return 0;
}
맞은 코드(스택 사용)
#include <iostream>
#include <stack>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
stack<int> s;
int* num = (int*)malloc(sizeof(int) * n);
int* ans = (int*)calloc(n, sizeof(int));
for (int i = 0; i < n; i++)
cin >> num[i];
for (int i = 0; i < n; i++) {
if (s.empty())
s.push(i);
while (!s.empty() && num[s.top()] < num[i]) {
ans[s.top()] = num[i];
s.pop();
}
s.push(i);
}
for (int i = 0; i < n; i++) {
if (ans[i] == 0)
cout << -1 << ' ';
else
cout << ans[i] << ' ';
}
free(num); free(ans);
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; i++) {
int t;
cin >> t;
v.push_back(t);
}
for (int i = 0; i < n; i++) {
int j = i;
bool check = false;
while (j < n) {
if (v[i] < v[j]) {
cout << v[j] << ' ';
check = true;
break;
}
j++;
}
if (!check)
cout << -1 << ' ';
}
return 0;
}
#include <iostream>
#include <stack>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
stack<int> s;
int* num = (int*)malloc(sizeof(int) * n);
int* ans = (int*)calloc(n, sizeof(int));
for (int i = 0; i < n; i++)
cin >> num[i];
for (int i = 0; i < n; i++) {
if (s.empty())
s.push(i);
while (!s.empty() && num[s.top()] < num[i]) {
ans[s.top()] = num[i];
s.pop();
}
s.push(i);
}
for (int i = 0; i < n; i++) {
if (ans[i] == 0)
cout << -1 << ' ';
else
cout << ans[i] << ' ';
}
free(num); free(ans);
return 0;
}
n이 커지니 이중 반복문은 시간 초과가 발생했다. 스택 문제인걸 몰랐다면 시간 초과를 어떻게 해결해야할지 정말 막막했을 것 같다ㅠㅠ.. 좀 더 노력해서 공부해야지!
Author And Source
이 문제에 관하여(백준 17298번(by C++)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@lah1203/백준-17298번by-C저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)