Cod sursa(job #3355450)

Utilizator alexanca_Alexandru anca alexanca_ Data 22 mai 2026 20:09:35
Problema Problema rucsacului Scor 10
Compilator java Status done
Runda Arhiva educationala Marime 2.02 kb
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    // Totul este static, evitam orice alocare de tip obiect
    static InputStream in;
    static byte[] buffer = new byte[4096]; // Buffer redus la 4KB
    static int head = 0;
    static int tail = 0;

    static int nextInt() throws Exception {
        int c = read();
        while (c <= 32) {
            c = read();
        }
        int res = 0;
        while (c > 32) {
            res = res * 10 + (c - '0');
            c = read();
        }
        return res;
    }

    static int read() throws Exception {
        if (head >= tail) {
            head = 0;
            tail = in.read(buffer, 0, buffer.length);
            if (tail <= 0) return -1;
        }
        return buffer[head++];
    }

    public static void main(String[] args) throws Exception {
        in = new FileInputStream("rucsac.in");

        int n = nextInt();
        int g = nextInt();

        int[] dp = new int[g + 1];

        for (int i = 0; i < n; i++) {
            int w = nextInt();
            int p = nextInt();

            for (int j = g; j >= w; j--) {
                int val = dp[j - w] + p;
                if (val > dp[j]) {
                    dp[j] = val;
                }
            }
        }
        in.close();

        // Afisare manuala, fara a folosi String-uri
        OutputStream out = new FileOutputStream("rucsac.out");
        int ans = dp[g];

        if (ans == 0) {
            out.write('0');
        } else {
            // Un vector mic pentru a stoca cifrele invers
            byte[] digits = new byte[15];
            int len = 0;
            while (ans > 0) {
                digits[len++] = (byte) ((ans % 10) + '0');
                ans /= 10;
            }
            // Scriem cifrele in ordinea corecta direct in fisier
            for (int i = len - 1; i >= 0; i--) {
                out.write(digits[i]);
            }
        }
        out.write('\n');
        out.close();
    }
}