Cod sursa(job #3356341)

Utilizator rares89_Dumitriu Rares rares89_ Data 31 mai 2026 04:21:21
Problema Ghiozdan Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.49 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, g;
int count_w[205];
int dp[75005];
int dp_prev[75005];
short* items_taken[205];

int main() {
    fin >> n >> g;
    
    for (int i = 1; i <= n; ++i) {
        int w;
        fin >> w;
        count_w[w]++;
    }
    fin.close();
    
    // Inițializare DP pentru număr minim de obiecte
    for (int j = 1; j <= g; ++j) {
        dp[j] = 1e9;
    }
    dp[0] = 0;
    
    for (int w = 1; w <= 200; ++w) {
        if (count_w[w] == 0) continue;
        
        // Alocăm rândul doar dacă avem obiecte cu greutatea 'w'
        items_taken[w] = new short[g + 1]();
        
        for (int j = 0; j <= g; ++j) {
            dp_prev[j] = dp[j];
        }
        
        for (int j = w; j <= g; ++j) {
            // Opțiunea 1: Ne formăm din starea veche, adăugând exact 1 obiect de greutate w
            if (dp_prev[j - w] != 1e9) {
                if (dp_prev[j - w] + 1 < dp[j]) {
                    dp[j] = dp_prev[j - w] + 1;
                    items_taken[w][j] = 1;
                } else if (dp_prev[j - w] + 1 == dp[j]) {
                    if (1 < items_taken[w][j]) {
                        items_taken[w][j] = 1;
                    }
                }
            }
            
            // Opțiunea 2: Ne formăm din starea curentă (adică adăugăm obiecte w adiționale)
            if (dp[j - w] != 1e9 && items_taken[w][j - w] < count_w[w]) {
                int cand = dp[j - w] + 1;
                short used = items_taken[w][j - w] + 1;
                
                if (cand < dp[j]) {
                    dp[j] = cand;
                    items_taken[w][j] = used;
                } else if (cand == dp[j]) {
                    if (used < items_taken[w][j]) {
                        items_taken[w][j] = used;
                    }
                }
            }
        }
    }
    
    int best_g = 0;
    for (int j = g; j >= 0; --j) {
        if (dp[j] != 1e9) {
            best_g = j;
            break;
        }
    }
    
    fout << best_g << " " << dp[best_g] << "\n";
    
    int curr_j = best_g;
    for (int w = 200; w >= 1; --w) {
        if (count_w[w] == 0) continue;
        
        int take_count = items_taken[w][curr_j];
        for (int k = 0; k < take_count; ++k) {
            fout << w << "\n";
        }
        curr_j -= take_count * w;
    }
    
    return 0;
}