Advertisement
Josif_tepe

Untitled

Jul 1st, 2025
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4. int p,m;
  5. int n;
  6. const int maxn=51;
  7. const int INF=2e9;
  8.  
  9. int x[maxn];
  10. int dp[maxn][1005];
  11. int rec(int at,int position){
  12.     if(at==n){
  13.         return position;
  14.     }
  15.     if(dp[at][position] != -1) {
  16.         return dp[at][position];
  17.     }
  18.     int res=-INF;
  19.     if(position+x[at]<=m){
  20.         res=max(res,rec(at+1,position+x[at]));
  21.     }
  22.     if(position-x[at]>=0){
  23.         res=max(res,rec(at+1,position-x[at]));
  24.     }
  25.    
  26.     dp[at][position] = res;
  27.     return res;
  28. }
  29. int main()
  30. {
  31.     memset(dp, -1, sizeof dp);
  32.     cin>>p>>m;
  33.     cin>>n;
  34.     for(int i = 0;i<n;i++){
  35.         cin>>x[i];
  36.     }
  37.     int res=rec(0, p);
  38.     if(res==-INF){
  39.         cout<<-1;
  40.     }else{
  41.       cout<<res;
  42.     }
  43.     return 0;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement