头一回ac。。。,纪念一下
第一题,求由只由2 3 5组成数,从小到大第n个
public class P1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] dp = new int[1100]; dp[1] = 2; dp[2] = 3; dp[3] = 5; LinkedList<Integer> queue = new LinkedList<>(); queue.add(2); queue.add(3); queue.add(5); for (int i=4; i<=1000; ) { LinkedList<Integer> newQueue = new LinkedList<>(); while (queue.size() > 0) { if (i > 1000) break; Integer j = queue.removeFirst(); dp[i++] = j*10+2; dp[i++] = j*10+3; dp[i++] = j*10+5; newQueue.add(j*10+2); newQueue.add(j*10+3); newQueue.add(j*10+5); } queue = newQueue; } while (scanner.hasNextInt()) { int n = scanner.nextInt(); System.out.println(dp[n]); } } }第二题,滚小球,dp,自下向上
public class P2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextInt()) { int n = scanner.nextInt(); int[][] arr = new int[n][2*n-1]; for (int i=0; i<n; i++) { for (int j=n-1-i; j<=n-1+i; j++) { arr[i][j] = scanner.nextInt(); } } int[][] dp = new int[n][2*n-1]; for (int i=0; i<2*n-1; i++) { dp[n-1][i] = arr[n-1][i]; } for (int i=n-2; i>=0; i--) { for (int j=n-1-i; j<=n-1+i; j++) { dp[i][j] = Math.max(Math.max(dp[i+1][j-1], dp[i+1][j]), dp[i+1][j+1]) + arr[i][j]; } } System.out.println(dp[0][n-1]); } } }
全部评论
(0) 回帖