SGU 104 Little shop of flowers

题目大意:n朵花,m个花瓶。第i朵花插入到第j个花瓶里可以获得价值cost[i][j]。第i朵花必须插在第i+1朵花的前面。求最大价值,并输出方案。

分析:

对于求最大价值,考虑第j个花瓶,有插花或者不插花两种可能,设dp[i][j]表示前i朵花插入倒前j个花瓶中所能获得的最大价值,则可以得出状态转移方程:dp[i][j]=max(dp[i][j-1],dp[i-1][j-1]+cost[i][j])。即dp[i][j]取第j个花瓶不插花与插花的较大值。

对于输出方案,用pos[i][j]来记录第i个花瓶所插的位置。递归输出即可。



import java.util.Scanner;

public class Solution{
    public static int dp[][] = new int[110][110], cost[][] = new int[110][110],
            pos[][] = new int[110][110], m, n;

    public static void printf(int i, int j) {
        if (i != 1) {
            printf(i - 1, pos[i][j] - 1);
            System.out.print(" " + pos[i][j]);
        } else {
            System.out.print(pos[i][j]);
            return;
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            n = in.nextInt();
            m = in.nextInt();
            int i, j;
            for (i = 1; i <= n; ++i)
                for (j = 1; j <= m; ++j)
                    cost[i][j] = in.nextInt();
            for(i=0;i<=n;++i)
                for(j=0;j<=m;++j) dp[i][j]=-200;
            for (j = 1; j <= m; ++j) {
                if (dp[1][j - 1] > cost[1][j]) {
                    dp[1][j] = dp[1][j - 1];
                    pos[1][j] = pos[1][j - 1];
                } else {
                    dp[1][j] = cost[1][j];
                    pos[1][j] = j;
                }
            }
            for (i = 2; i <= n; ++i)
                for (j = i; j <= m; ++j) {
                    if (dp[i][j - 1] > dp[i - 1][j - 1] + cost[i][j]) {
                        dp[i][j] = dp[i][j - 1];
                        pos[i][j] = pos[i][j - 1];
                    } else {
                        dp[i][j] = dp[i - 1][j - 1] + cost[i][j];
                        pos[i][j] = j;
                    }
                }
            System.out.println(dp[n][m]);
            printf(n, m);
        }
        in.close();
    }
}


你可能感兴趣的:(SGU 104 Little shop of flowers)