java - dynamic programming 01

Get maximum gift value. Use the idea of ​​dynamic programming to complete the writing of dp. Don't talk nonsense and go directly to the code. I don’t have enough knowledge of it, the code may be a bit rough~

For example:

There is such a set of data (value):

2 3 4 5

3 5 7 8

2 6 5 4

Ask how to go from the upper left corner to the lower right corner so that it can get the maximum value.

import java.util.*;

 public class test10 {     static int[][]c;     public static void main(String[] args) {         Scanner in=new Scanner(System.in);         int m=in.nextInt();//line         int n=in .nextInt();//column         int[][]a=new int[m][n];         for(int i=0;i<m;i++){//value distribution map             for(int j=0; j<n;j++){                 a[i][j]=in.nextInt();             }         }         System.out.println(dp(a));         System.out.println("***** route For:******");         line(c);     }     static int dp(int[][]a){//dp finds the maximum value         int m=a.length;         int n=a[m-1 ].length;         int[][]f=a;//Array of record value



















        for(int i=0;i<n-1;i++){//Process the first row
            f[0][i+1]=f[0][i]+f[0][i+1];
        }
        for(int i=0;i<m-1;i++){//Process the first column
            f[i+1][0]=f[i][0]+f[i+1][0] ;
        }
        for(int i=1;i<m;i++){//Process the remaining rows and columns
            for(int j=1;j<n;j++){                 int x=f[i][j-1 ]+f[i][j];                 int y=f[i-1][j]+f[i][j];                 f[i][j]=Math.max(x, y);             }         }         c=f;         return f[m-1][n-1];//return the last     }     static void line(int[][]a){//find the route         int m=a.length;//line         int n=a[0].length;//column         int i=m-1,j=n-1;












        int[][]b=new int[a.length][a[0].length];//mark array
        while(i!=0||j!=0){             b[i][j]=1 ;             if(j==0){//The first column                 for(int k=i;k>=0;k--){                     b[k][j]=1;                 }                 break;             }             if(i== 0){//The first line                 for(int k=j;k>=0;k--){                     b[i][k]=1;                 }                 break;             }             int y=a[i-1][j ];//Last line             int x=a[i][j-1];//Left column             if(x>y){                 j=j-1;             }             else



















                i=i-1;
        }
        for(int k=0;k<m;k++){
            for(int l=0;l<n;l++){
                System.out.print(b[k][l]+" ");
            }
            System.out.println();
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_52705208/article/details/123690134