2018.1.29【 AtCoder Beginner Contest 087-C 】解题报告(简单dp)

C - Candies


Time limit : 2sec / Memory limit : 256MB

Score : 300 points

Problem Statement

We have a 2×N grid. We will denote the square at the i-th row and j-th column (1i21jN) as (i,j).

You are initially in the top-left square, (1,1). You will travel to the bottom-right square, (2,N), by repeatedly moving right or down.

The square (i,j) contains Ai,j candies. You will collect all the candies you visit during the travel. The top-left and bottom-right squares also contain candies, and you will also collect them.

At most how many candies can you collect when you choose the best way to travel?

Constraints

  • 1N100
  • 1Ai,j100 (1i21jN)

Input

Input is given from Standard Input in the following format:

N
A1,1 A1,2  A1,N
A2,1 A2,2  A2,N

Output

Print the maximum number of candies that can be collected.


Sample Input 1

Copy
5
3 2 2 4 1
1 2 2 2 1

Sample Output 1

Copy
14

The number of collected candies will be maximized when you:

  • move right three times, then move down once, then move right once.

Sample Input 2

Copy
4
1 1 1 1
1 1 1 1

Sample Output 2

Copy
5

You will always collect the same number of candies, regardless of how you travel.


Sample Input 3

Copy
7
3 3 4 5 4 5 3
5 3 4 4 2 3 2

Sample Output 3

Copy
29

Sample Input 4

Copy
1
2
3

Sample Output 4

Copy
5

【题目大意】

2*N个格子,每个格子里均含有不同数量的蜡烛。每一次只能向右或者向下走,问从(1,1)走到(2,N)最多能收集多少根蜡烛(包括首尾)。

【解题思路】

入门DP,简化成2*N了,状态转移方程:dp[i][j]=max(dp[i-1][j],dp[i][j-1])+a[i][j]

【解题代码】

#include 
#include 
#include 
using namespace std;
//dp   dp[i][j]=max(dp[i-1][j],dp[i][j-1])+a[i][j]
const int maxn=1e2+10; 
int n;
int a[maxn][maxn];
int dp[maxn][maxn];

int max(int a,int b)
{
	return a>b?a:b;
 } 

void solve()
{
	dp[1][1]=a[1][1];
	for(int i=1;i<=2;i++)
	{
		for(int j=1;j<=n;j++)
		{
			if(i==1)
				dp[i][j]=dp[i][j-1]+a[i][j];
			else
				dp[i][j]=max(dp[i-1][j],dp[i][j-1])+a[i][j]; 
		}
	}
} 
int main()
{
	while(~scanf("%d",&n))
	{
	
	memset(a,0,sizeof(a));
	memset(dp,0,sizeof(dp));
	for(int i=1;i<=2;i++)
	{
		for(int j=1;j<=n;j++)
		{
			scanf("%d",&a[i][j]);
		}
	}
	solve();
	printf("%d\n",dp[2][n]);
}
	return 0;
}

【收获与反思】

第一次小比赛实战应用dp,看了看大神们也都是dp秒出说明思路是正确的。能写好状态转移方程就行。

你可能感兴趣的:(AtCoder,DP)