Cod sursa(job #3221448)

Utilizator Victor_9Diaconescu Victor Victor_9 Data 7 aprilie 2024 10:49:46
Problema Zebughil Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.08 kb
#include <bits/stdc++.h>
using namespace std;
const int nmax = 19, gmax = 20000001;
#define ll long long 

ifstream fin("zebughil.in");
ofstream fout("zebughil.out");

ll T = 3, n, g, dp[gmax], ok[nmax], poz, maxx, numara, v[nmax], toate0;

bool comp(int a, int b){
    if(a > b) return 1;
    return 0;
}

int main()
{
    while(T){
        fin>>n>>g;
        
        maxx = 0;
        numara = 0;
        toate0 = 0;
        
        for(int i=1;i<=n;i++){
            fin>>v[i];
            dp[i] = 0;
            ok[i] = 0;
            if(v[i] == 0){
                ok[i] = 1;
            }
            if(v[i] != 0){
                toate0 = 1;
            }
        }
        
    if(toate0 == 1){
        sort(v + 1 , v + n + 1, comp);
        
        for(int i=1;i<=n;i++){
            if(ok[i] == 0){
                
                //resetam dp-ul
                for(ll l=0;l<=g;l++){
                    dp[l] = 0;
                }
                
                numara++;
                ok[i] = 1;
                
                //facem dp 
                dp[0] = 1;
                
                for(int j=i+1;j<=n;j++){
                    for(ll l=g-v[i];l>=0;l--){
                        if(l - v[j] >= 0 && dp[l - v[j]] == 1 && ok[j] == 0){
                            dp[l] = 1;
                        }
                    }
                }
                
                //gasim suma maxima
                for(ll l=g-v[i];l>=0;l--){
                    if(dp[l] == 1){
                        maxx = l ;
                        break;
                    }
                }
                
                //reconstruim
                while(maxx){
                    for(int j=i+1;j<=n;j++){
                        if(maxx - v[j] >= 0 && dp[maxx - v[j]] == 1 && ok[j] == 0){
                            maxx -= v[j];
                            ok[j] = 1;
                        }
                    }
                }
                
            }
        }
        
        fout<<numara<<"\n";
        
        T --;
    }else{
        fout<<1<<"\n";
    }
    
    }
    
    
}