ann8497

collect max coins/ approach 2 Samsung

Sep 10th, 2019
2,047
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. /*
  2. 4
  3. 7
  4. 1 2 0 0 1
  5. 2 0 0 1 0
  6. 0 1 2 0 1
  7. 1 0 0 2 1
  8. 0 2 1 0 1
  9. 0 1 2 2 2
  10. 1 0 1 1 0
  11. 5
  12. 1 1 0 0 0
  13. 1 2 2 2 1
  14. 1 1 2 2 1
  15. 2 2 2 1 2
  16. 2 2 0 2 0
  17. 6
  18. 2 2 2 2 2
  19. 0 0 0 0 0
  20. 0 0 2 0 0
  21. 2 0 0 0 2
  22. 0 0 0 0 0
  23. 1 2 2 2 1
  24. 12
  25. 2 2 2 2 2
  26. 1 1 0 1 1
  27. 0 1 0 1 0
  28. 1 0 1 0 1
  29. 2 2 0 0 2
  30. 1 1 0 0 1
  31. 2 2 2 2 2
  32. 1 1 0 1 0
  33. 0 1 0 1 0
  34. 1 0 1 0 1
  35. 2 2 2 2 2
  36. 2 2 0 1 1
  37.  
  38. Answers
  39. 6
  40. 3
  41. -1
  42. 8
  43.  
  44. */
  45.  
  46. #include<iostream>
  47. using namespace std;
  48.  
  49. int n;
  50. int a[15][5];
  51. int ans;
  52.  
  53. int dx[] = {-1,0,1};
  54.  
  55. bool valid(int r, int c){
  56.     return (c>=0 && c<5 && r>=0 && r<n);
  57. }
  58.  
  59. void solve(int r, int c, int points , int power, int magic){
  60.    
  61.    
  62.     /* important to find the max at every call
  63.      to get the intermediate maximum also*/
  64.     ans = max(ans,points);
  65.    
  66.     if(r==0){
  67.         ans = max(ans,points);
  68.         return;
  69.     }
  70.    
  71.     for(int i = 0; i<3; i++){
  72.        
  73.         int y = c + dx[i];
  74.         int x = r - 1;
  75.    
  76.         if(valid(x,y)){
  77.         if(a[x][y] == 2){
  78.             if(magic){
  79.                 solve(x,y,points,5,0);
  80.             }
  81.             if(points > 0)
  82.             solve(x,y,points-1,power-1,magic);
  83.            
  84.             if(power > 0)
  85.             solve(x,y,points,power-1,0);
  86.            
  87.             /*base case  don't forget this*/
  88.             if(points == 0 && power <= 0 && magic == 0){
  89.                 ans = max(ans,points);
  90.                 return;
  91.             }
  92.         }
  93.        
  94.         if(a[x][y] == 1)solve(x,y,points+1,power-1,magic);
  95.         if(a[x][y] == 0)solve(x,y,points,power-1,magic);
  96.         }
  97.     }
  98. }
  99.  
  100. int main(){
  101.    
  102.    
  103.     int t; cin>>t;
  104.     while(t--){
  105.     cin>>n;
  106.    
  107.     for(int i = 0; i<n; i++){
  108.         for(int j =0; j<5; j++){
  109.             cin>>a[i][j];
  110.         }
  111.     }
  112.    
  113.     ans = -1;
  114.     solve(n,2,0,0,1);
  115.     if(ans == 0)ans = -1;
  116.     cout<<ans<<endl;
  117.     }
  118.     return 0;
  119. }
Add Comment
Please, Sign In to add comment