【AtCoder-3881】解题报告(简单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 (1≤i≤2, 1≤j≤N) 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 - 1≤N≤100 - 1≤Ai,j≤100 (1≤i≤2, 1≤j≤N)

### 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

5
3 2 2 4 1
1 2 2 2 1

### Sample Output 1

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

4
1 1 1 1
1 1 1 1

### Sample Output 2

5

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

### Sample Input 3

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

### Sample Output 3

29

### Sample Input 4

1
2
3

### Sample Output 4

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]

# 解题代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <sstream>
#include <bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<n;++i)
#define per(i,a,n) for(int i=n-1;i>=a;--i);
#define ms(x,a) memset((x),a,sizeof((x)))
#define INF 0x3f3f3f3f
#define eps 1e-8
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define np next_permutation
#define gapline cout<<"##======================##"<<endl
using namespace std;
const int maxn=300;
const int maxl=26;
const int maxm=1e5+5;

typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> pii;
int n,m;
int dp[maxn][maxn],a[maxn][maxn];
void solve(){
rep(i,1,n+1){
rep(j,1,m+1){
dp[i][j]=max(dp[i-1][j],dp[i][j-1])+a[i][j];
}
}
}

int main(){
ios::sync_with_stdio(false);
while(cin>>m){
ms(dp,0);
n=2;

rep(i,1,n+1){
rep(j,1,m+1) cin>>a[i][j];
}
solve();
cout<<dp[2][m]<<endl;

}
}

# 收获与反思

  • 第一次小比赛实战应用dp,看了看大神们也都是dp秒出说明思路是正确的。能写好状态转移方程就行。
  • 2018.8.23更新 代码优化,利用dp外围空白。