λ¬Έμ
μ½λ
#include <iostream>
#include <stack>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int N; cin>>N;
stack<pair<int,int>>st; // {ν λ²νΈ, λμ΄}
for(int i=0; i<N; i++){
int height; cin>>height;
while(!st.empty()){
if(st.top().second>height){
cout<<st.top().first<<' ';
break;
}
st.pop();
}
if(st.empty()) cout<< 0 <<' ';
st.push({i+1,height});
}
}
νμ΄
stackμ {ν λ²νΈ, λμ΄} νμμΌλ‘ μ μ₯μ νκΈ° μν΄ pair νμ μΌλ‘ μ μΈν©λλ€.
μ‘μ νμ μ λ ₯λ°μ λλ§λ€ stackμ μ°Ύλλ°, λ§μ½ νμ¬ μ€νμ΄ λΉμ΄μμ§ μλ€λ©΄ νμ¬ μ‘μ νμ λμ΄λ³΄λ€ ν° λμ΄κ° λμ¬ λκΉμ§ μ€νμ λΉμκ°λλ€. λ§μ½ νμ¬ μ‘μ νλ³΄λ€ ν° λμ΄λ₯Ό λ°κ²¬νλ€λ©΄ κ·Έ μ‘μ νμ μ§μ°μ§ λ§μμΌ ν©λλ€.
κ·Έ ν, whileλ¬Έμ λΉ μ Έλμμ λ μ€νμ΄ λΉμ΄μλ€λ©΄ νμ¬ μ‘μ νλ³΄λ€ λμ νμ΄ μλ€λ λ§μ΄ λκΈ°μ 0μ μΆλ ₯ν©λλ€.
κ·Έλ¦¬κ³ κ³΅ν΅μ μΌλ‘ νμ¬μ μ‘μ νμ μ€νμ λ£μ΄μ€λλ€.
μ μΌ μ²μ νμμλλ μλμ κ°μ΄ μ‘°κΈ λλ½κ² νμμμ΅λλ€.
#include <iostream>
#include <stack>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int N; cin>>N;
stack<pair<int,int>>st; // {ν λ²νΈ, λμ΄}
for(int i=0; i<N; i++){
int height; cin>>height;
if(i==0){
cout<<0<<' ';
st.push({i+1, height});
continue;
}
while(!st.empty()){
if(st.top().second>height){
cout<<st.top().first<<' ';
st.push({i+1, height});
break;
}
else{
bool flag = false;
while(!st.empty()){
if(st.top().second<height) st.pop();
else{
flag = true;
cout<<st.top().first<<' ';
break;
}
}
if(!flag) cout<<0<<' ';
st.push({i+1, height});
break;
}
}
}
}
'Algorithm π§π»βπ» > λ°±μ€(BOJ)' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[λ°±μ€,c++] 18115λ² - μΉ΄λ λκΈ° (0) | 2022.06.19 |
---|---|
[λ°±μ€,c++] 5397λ² - ν€λ‘κ±° (0) | 2022.06.03 |
[λ°±μ€,c++] 1918λ² - νμ νκΈ°μ (0) | 2022.06.03 |
[λ°±μ€,c++] 2800λ² - κ΄νΈ μ κ±° (0) | 2022.06.03 |
[λ°±μ€,c++] 17141λ² - μ°κ΅¬μ 2 (0) | 2022.05.27 |
[λ°±μ€,c++] 1331λ² - λμ΄νΈ ν¬μ΄ (0) | 2022.05.08 |
λκΈ