Advertisement
Josif_tepe

Untitled

Jun 23rd, 2025
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. #include <vector>
  4. using namespace std;
  5. const int maxn = 22;
  6. const int INF = 1e9;
  7. int n;
  8. int mat[maxn][3];
  9. int dp[maxn][3][3];
  10. int rec(int at, int last_color, int first_color) {
  11.     if(at == n) {
  12.         return 0;
  13.     }
  14.     if(dp[at][last_color][first_color] != -1) {
  15.         return dp[at][last_color][first_color];
  16.     }
  17.     int res = INF;
  18.     if(at == n - 1) {
  19.         for(int color = 0; color <= 2; color++) {
  20.             if(color != last_color and color != first_color) {
  21.                 res = min(res, rec(at + 1, color, first_color) + mat[at][color]);
  22.             }
  23.         }
  24.     }
  25.     else {
  26.         for(int color = 0; color <= 2; color++) {
  27.             if(color != last_color) {
  28.                 res = min(res, rec(at + 1, color, first_color) + mat[at][color]);
  29.             }
  30.         }
  31.     }
  32.     dp[at][last_color][first_color] = res;
  33.     return res;
  34. }
  35. int main() {
  36.     ios_base::sync_with_stdio(false);
  37.     cin >> n;
  38.    
  39.     for(int i = 0; i < n; i++) {
  40.         cin >> mat[i][0] >> mat[i][1] >> mat[i][2];
  41.     }
  42.     memset(dp, -1, sizeof dp);
  43.    
  44.     int res = rec(1, 0, 0) + mat[0][0];
  45.     res = min(res, rec(1, 1, 1) + mat[0][1]);
  46.     res = min(res, rec(1, 2, 2) + mat[0][2]);
  47.    
  48.     cout << res << endl;
  49.    
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement