- ์ด ๊ธ์ c++๋ก ํ์ด๋ฅผ ์์ฑํ์์ต๋๋ค.
๋ฌธ์
์์
ํ์ด
- BFS๋ฅผ ์ฌ์ฉํ ์ ์์ง๋ง DP๋ฅผ ํ์ฉํ์ฌ ๊ณต๊ฐ๋ณต์ก๋๋ฅผ ์ค์ผ ์ ์์ต๋๋ค.
- if i%2 != 0 && i%3 != 0, D[i] = D[i-1]+1
- if i%2 == 0 && i%3 != 0, D[i] = min(D[i-1], D[i/2]) + 1
- if i%2 == 0 && i%3 == 0, D[i] = min(D[i-1], D[i/2], D[i/3]) + 1
- ๋ฐฉ๋ฒ์ ์ถ๋ ฅํ๊ธฐ ์ํด์๋ ๊ทธ ์ ์ซ์๋ฅผ ๋ด๋ prev ๋ฐฐ์ด์ ๋ง๋ค์ด์ผ ํฉ๋๋ค. 10 => prev[10] = 9, prev[9] = 3, prev[3] = 1
#include<iostream>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int arr[1000005];
int prev[10000005];
arr[1] = 0;
prev[1] = 0;
int num;
cin>>num;
for(int i=2;i<=num;i++){
arr[i] = arr[i-1]+1;
prev[i] = i-1;
if(i%2 == 0){
if(arr[i]>(arr[i/2]+1)){
arr[i] = arr[i/2]+1;
prev[i] = i/2;
}
}
if(i%3 == 0){
if(arr[i]>(arr[i/3]+1)){
arr[i] = arr[i/3]+1;
prev[i] = i/3;
}
}
}
cout<<arr[num]<<"\n";
do{
cout<<num<<' ';
num = prev[num];
}while(num!=0);
}
- ์ถ๊ฐ๋ก ๊ถ๊ธํ ์ ์ด๋ ์์ ํ ๋ถ๋ถ ์์ผ๋ฉด ๋๊ธ๋ก ๋จ๊ฒจ์ฃผ์ธ์.