题解 | #【模板】01背包#

【模板】01背包

https://www.nowcoder.com/practice/9bb79a902fb74ec9adde6e4e8fd1a5d1

import java.io.*;
import java.util.*;
import java.math.BigInteger;

public class Main {
    static void solve() {
        int n = in.nextInt(),m = in.nextInt();
        int[] w = new int[n+10], v = new int[n+10];
        int[] dp = new int[m+10];
        for(int i=1;i<=n;i++) {
            w[i] = in.nextInt();
            v[i] = in.nextInt();
        }
        for(int i=1;i<=n;i++) {
            for(int j=m;j>=w[i];j--) {
                dp[j] = Math.max(dp[j],dp[j-w[i]]+v[i]);
            }
        }
        out.println(dp[m]);
    }

    public static void main(String[] args) {
        int T = in.nextInt();
        while(T-->0) {
            solve();
        } 
        out.flush();
    }

    static FastReader in = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);

    static class FastReader {
        static BufferedReader br;
        static StringTokenizer st;

        FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            String str = "";
            while (st == null || !st.hasMoreElements()) {
                try {
                    str = br.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                st = new StringTokenizer(str);
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }
    }
}

全部评论

相关推荐

无敌虾孝子:喜欢爸爸还是喜欢妈妈
点赞 评论 收藏
分享
11-06 10:58
已编辑
门头沟学院 嵌入式工程师
双非25想找富婆不想打工:哦,这该死的伦敦腔,我敢打赌,你简直是个天才,如果我有offer的话,我一定用offer狠狠的打在你的脸上
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务