ALG/ALG Solve
C++) 백준 2635번 수 이어가기
jh2ee
2023. 1. 2. 20:41
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include <queue> | |
using namespace std; | |
int main(){ | |
ios::sync_with_stdio(false); | |
cout.tie(NULL); cin.tie(NULL); | |
queue<int> q,ans; // q:원소 저장, ans:최대인 경우 저장 | |
int n; | |
int m1,m2,temp; // m1뺄셈 대상, m2뺄 수, temp그 결과 | |
cin>>n; // 수 입력 | |
if(n==1) cout<<"4\n1 1 0 1\n"; | |
else{ | |
for(int i=1;i<n;i++) // 0~n까지 반복해 경우 구함 | |
{ // 나열되는 수의 길이를 저장, 최대인 경우 수의 나열 또한 저장 | |
m1=n; q.push(m1); | |
m2=n-i; q.push(m2); | |
while(1){ //음수 출력시 종료 | |
temp=m1-m2; | |
if(temp<0) break; | |
m1=m2; m2=temp; // | |
q.push(temp); | |
} | |
if(q.size()>ans.size()){ | |
ans=q; // q의 원소를 ans로 복사 | |
} | |
q=queue<int>(); // q초기화 | |
} | |
cout<<ans.size()<<"\n"; | |
while(!ans.empty()){ | |
//출력 | |
cout<<ans.front()<<" "; | |
ans.pop(); | |
} | |
cout<<"\n"; | |
} | |
} |
queue를 이용하여 구현하였다.
STL queue의 메소드, 복사, 초기화 기법을 상기할 수 있었다.
queue를 초기화 할 때 루프를 이용해 pop하지 않고 새로 선언하여 초기화를 할 수도 있다.