Introduction to "Apple Collection" Dynamic planning

Source: Internet
Author: User

Descriptive narrative of the problem

There are n*m on the plane, and a certain number of apples are placed in each lattice. You start at the upper left corner of the grid, each step can just go down or to the right, every time you go to a grid to collect the apples in the lattice, so down, you can collect the maximum number of apples.

Input:

Enter the number of rows and columns in the first row

Then enter the number of apples in each grid row by line

Output:

The maximum number of apples that can be received.

Thinking analysis

This is a typical two-dimensional array dp problem

Basic Status:

The number of apples collected is dp[x][y] when you reach the grid in column y of line X.

Transfer equation:

Because you can only walk to the right or down, so when you get to the grid in row y of line x, you may have arrived at the grid from row x-1 or column x y-1, and we will only collect the most apple option.

So:

Dp[x][y] = max (if (x>0) dp[x-1][y], if (y>0) dp[x][y-1])

Writing code

Show you code:

#include <iostream> #include <string.h>using namespace Std;int a[100][100];int dp[100][100];int m,n;void DP _fun (int x,int y) {dp[x][y] = A[x][y];int max = 0;if (x > 0 && Max < dp[x-1][y]) {max = dp[x-1][y];} if (Y > 0 && Max < dp[x][y-1]) {max = dp[x][y-1];} Dp[x][y] + = max;if (x<m-1) {dp_fun (x+1,y);}  if (y<n-1) {dp_fun (x,y+1);} return;} int main () {memset (dp,0,sizeof (DP)); cin>>m>>n;for (int i=0;i<m;i++) {for (int j=0;j<n;j++) {cin> >A[I][J];}} Dp_fun (0,0); for (int. i=0;i<m;i++) {for (int j=0;j<n;j++) {cout<<dp[i][j]<< "\ T";} Cout<<endl;} return 0;}

Demo Sample data:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.