Cod sursa(job #3355556)

Utilizator vickgoodmanSava Victor vickgoodman Data 23 mai 2026 00:52:32
Problema Problema rucsacului Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 1.95 kb
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

class Main {
    // Clasă ultra-ușoară pentru citire (consumă doar 8KB de memorie pentru buffer)
    static class FastScanner {
        InputStream is;
        byte[] buffer = new byte[8192];
        int head = 0, tail = 0;

        public FastScanner(String fileName) throws IOException {
            is = new FileInputStream(fileName);
        }

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

        public int nextInt() throws IOException {
            int c = read();
            // Ignorăm spațiile goale și new-lines
            while (c <= ' ') {
                if (c == -1) return -1;
                c = read();
            }
            int res = 0;
            // Construim numărul cifră cu cifră
            while (c > ' ') {
                res = res * 10 + c - '0';
                c = read();
            }
            return res;
        }
    }

    public static void main(String[] args) throws IOException {
        FastScanner in = new FastScanner("rucsac.in");
        // FileWriter este mult mai eficient d.p.d.v. al memoriei decât PrintWriter
        FileWriter out = new FileWriter("rucsac.out");

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

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

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

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

        // Scriem direct rezultatul transformat în String, urmat de o linie nouă
        out.write(dp[g] + "\n");
        out.close();
    }
}