AcWintg 1015. 摘花生 (动态规划)

Problem

这个题和数字金字塔三角形就有点像,重要的是确定最后一步的状态,也是典型的线性dp问题,也就是根据下标增进来递推的问题。

因为只能往右和下走,最后一步只能从左边或者上面走过来,于是有递推式。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 110;
    static int a[][] = new int[N][N], f[][] = new int[N][N];

    public static void main(String[] args) throws Exception {

        int T = Integer.parseInt(br.readLine());
        while (T-- > 0) {
            String[] s = br.readLine().split(" ");
            int n = Integer.parseInt(s[0]);
            int m = Integer.parseInt(s[1]);
            for (int i = 1; i <= n; i++) {
                s = br.readLine().split(" ");
                for (int j = 1; j <= m; j++)
                    a[i][j] = Integer.parseInt(s[j - 1]);
            }

            for (int i = 1; i <= n; i++)
                for (int j = 1; j <= m; j++)
                    f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) + a[i][j];

            pw.println(f[n][m]);
        }

        pw.flush();
        pw.close();
        br.close();
    }
}

发布了167 篇原创文章 · 获赞 3 · 访问量 3432

猜你喜欢

转载自blog.csdn.net/qq_43515011/article/details/104209157
今日推荐