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 <cstdio>
#include <cstring>
#include <cmath>
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秒出說明思路是正確的。能寫好狀態轉移方程就行。

發佈了40 篇原創文章 · 獲贊 1 · 訪問量 6256
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章