(dp)吉林大学ACM集训队选拔赛(重现赛) b Subset of Five

补一下之前的一道简单dp题,转移就是dp[i][j]=max(dp[i][j],dp[i-1][(j-x+5)%5]+a[i]);要么不选这个数,要么选这个数和之前的dp[i-1][(j-x+5)%5]加到一起

 链接:https://ac.nowcoder.com/acm/contest/5944/B
来源:牛客网
 

"Today is another day! I'm five." With the fail of unit tests, XiaoYang tiredly lies on the sofa. As we all know, XiaoYang is not good at implementing algorithms. The unit test is for a subset searching algorithm. Here is the task.

You are given a set A with n **distinct** integers a1,a2,⋯ ,ana_1, a_2, \cdots, a_na1​,a2​,⋯,an​. You should find a "five" subset S, so that the sum of numbers in S is maximized and the sum is divisible by 5. A set B={b1,b2,⋯ ,bm}B = \lbrace b_1, b_2, \cdots, b_m \rbraceB={b1​,b2​,⋯,bm​} of size m is called the subset of set A={a1,a2,⋯ ,an}A = \lbrace a_1, a_2, \cdots, a_n \rbraceA={a1​,a2​,⋯,an​} when bi∈Ab_i \in Abi​∈A holds for i=1,2,⋯ ,mi = 1, 2, \cdots, mi=1,2,⋯,m and all integers in B are distinct.

输入描述:

 

The first line contains integer n (n≤106)n ~ (n \leq 10^6)n (n≤106), the size of set A.

The second line contains n integers a1,a2,a3,⋯ ,an (0≤ai≤109)a_1, a_2, a_3, \cdots, a_n ~ (0 \leq a_i \leq 10^9)a1​,a2​,a3​,⋯,an​ (0≤ai​≤109).

输出描述:

Output the maximal sum of S.

示例1

输入

复制5 2 10 6 3 1

5
2 10 6 3 1

输出

复制20

20
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string>
#include<queue>
#include<string.h>
#include<map>
#define ll long long
//#define ll int
#include <iostream>
#include <math.h>
using namespace std;
#define maxn 1300005
#include<vector>
ll a[maxn],dp[maxn][10];
int main()
{
    memset(dp,-1,sizeof(dp));
    ll n;
    scanf("%lld",&n);
    for(ll i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
    }
    dp[1][a[1]%5]=a[1];
    for(ll i=2;i<=n;i++)
    {
        ll x=a[i]%5;
        for(ll j=0;j<5;j++) dp[i][j]=dp[i-1][j];
        dp[i][x]=max(dp[i][x],a[i]);
        for(ll j=0;j<5;j++)
        {
            if(dp[i-1][(j-x+5)%5]==-1) ;//dp[i][j]=dp[i-1][j];//上一个状态不存在
            else
            {
                dp[i][j]=max(dp[i][j],dp[i-1][(j-x+5)%5]+a[i]);
            }
        }
        /*for(int j=0;j<5;j++)
        {
            printf("dp[%d][%d]=%d\n",i,j,dp[i][j]);
        }
        printf("\n");*/
    }
    printf("%lld\n",dp[n][0]==-1?0:dp[n][0]);
}

猜你喜欢

转载自blog.csdn.net/qq_43497140/article/details/106949154
今日推荐