POJ 2385 tree off Apple problem DP algorithm

Source: Internet
Author: User

Test instructions: Tree 1 tree 2 will lose apples, cows to pick up, can only move w times, at the beginning of the tree 1 asked the maximum number of apples can be picked up?

Idea: dp[i][j] means I minute move J times pick up the maximum value of the apple

Example analysis

0,1 ... description even in tree 1 odd in tree 2

for (int i = 1; I <= n; i++)
{
scanf ("%d", &t[i]);
T[i]-= 1;
}
for (int i = 1; I <= n; i++)
for (int j = 0; J <= W; j + +)
{
if (j% 2) dp[i][j] = max (Dp[i-1][j], dp[i-1][j-1]) + t[i];
else dp[i][j] = max (Dp[i-1][j], dp[i-1][j-1]) +!t[i];
}

Here's a little trick, not every time you ask for data like 1 2 2, we put them all--1 and then we can look better.

Explain the two-sentence DP statement

DP[I][J] = max (Dp[i-1][j], dp[i-1][j-1]) represents the last time either in tree 1 or in tree 2, but I only need the maximum value between them

Code to solve the problem:

#include <iostream>#include<cstdio>#include<algorithm>using namespacestd;intdp[1010][ *];intt[1010];intMain () {intN, W; scanf ("%d%d", &n, &W);  for(inti =1; I <= N; i++) {scanf ("%d", &T[i]); T[i]-=1; }     for(inti =1; I <= N; i++)         for(intj =0; J <= W; J + +)        {            if(J%2) Dp[i][j] = max (Dp[i-1][J], Dp[i-1][j-1]) +T[i]; ElseDP[I][J] = max (Dp[i-1][J], Dp[i-1][j-1]) + !T[i]; } printf ("%d\n", Dp[n][w]);}

POJ 2385 tree off Apple problem DP algorithm

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.