import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); int n = sc.nextInt(); int[][] m_n = new int[m+1][n+1]; for (int i = 1; i < m+1; i++) { for (int j = 1; j < n+1; j++) { m_n[i][j] = sc.nextInt(); } } System.out.println(getResult(m_n,m,n)); } private static int getResult(int[][] m_n, int m, int n) { int[][] dp = new int[m+1][n+1]; for (int i = 0; i < n+1; i++) { dp[1][i] = m_n[1][i]; } for (int i = 2; i < m+1; i++) { dp[i][0] = 0; dp[i][1] = Math.max(m_n[i][1],dp[i-1][1]); for (int j = 2; j < n+1; j++) { dp[i][j] = Math.max(dp[i][j-1]+m_n[i-1][1],m_n[i][j]+m_n[i-1][1]); } } return dp[m][n]; } }
m, n = input().split() m, n = int(m), int(n) ma = [] for _ in range(m): tmp = [] for x in input().split(): tmp.append(int(x)) ma.append(tmp) opt = [0] * (n+1) for i in range(m): for j in range(n, 0, -1): tmp = 0 for k in range(0, n): if(k >= j): break tmp = max(tmp, ma[i][k]+opt[j-k-1]) opt[j] = max(tmp, opt[j]) print(max(opt)) 背包过了
while(1): n,m = map(int,input().split()) data = [] for i in range(n): data.append(list(map(int,input().split()))) # dp = [0] + data[0] for i in range(1,n): for j in range(m,0,-1): for k in range(1,j+1): dp[j] = max(dp[j],dp[j-k] + data[i][k-1]) print(dp) print(dp[m])
public class Main4 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Node[] node = new Node[n]; //表示关卡 for (int i = 0; i < n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); node[i] = new Node(a,b); } Arrays.sort(node,(o1,o2)->o1.v==o2.v?o2.point-o1.point:o1.v-o2.v); int sum = 0; for (Node nd : node) { if(nd.v==0){ sum+=nd.point; }else{ if(sum+nd.point<2*sum){ //用宝物 sum*=2; }else sum+=nd.point; //不用宝物 } } System.out.println(sum); } } class Node{ int point; //分数 int v; //是否有宝物 public Node(int point,int v){ this.point = point; this.v = v; } } 第二题,我这个不知道对不对,自测了几个用例都可以过,最后时间不够没提交上去