3.1.1. 피보나치 함수 ¶
#include<iostream> #include<utility> using namespace std; int arr[41][2] = { 0, }; pair<int,int> search(int num){ if(arr[num][0] + arr[num][1]){ return make_pair(arr[num][0], arr[num][1]); } pair<int,int> tmp1 = search(num-1); pair<int,int> tmp2 = search(num-2); arr[num][0] = tmp1.first + tmp2.first; arr[num][1] = tmp1.second + tmp2.second; return make_pair(arr[num][0], arr[num][1]); } int main(){ arr[0][0] = arr[1][1] = 1; int T; cin>>T; while(T--){ int n; cin>> n; search(n); printf("%d %d\n", arr[n][0],arr[n][1]); } }
3.1.2. RGB 거리 ¶
#include<iostream> #include<algorithm> using namespace std; int arr[1001][3] = {0,}; int w[1001][3] = {0,}; int main(){ int n; cin>>n; for(int i = 0; i<n; i++){ for(int j = 0; j<3; j++){ scanf("%d", &w[i][j]); } } arr[0][0] = w[0][0]; arr[0][1] = w[0][1]; arr[0][2] = w[0][2]; for(int i = 1; i<n; i++){ arr[i][0] = min(arr[i-1][1] + w[i][0], arr[i-1][2] + w[i][0]); arr[i][1] = min(arr[i-1][0] + w[i][1], arr[i-1][2] + w[i][1]); arr[i][2] = min(arr[i-1][0] + w[i][2], arr[i-1][1] + w[i][2]); } int tmp = min(arr[n-1][0],arr[n-1][1]); tmp = min(tmp,arr[n-1][2]); cout<<tmp<<endl; }