AcWing 1047. Candy

Due to its great contribution to the maintenance of world peace, Dzx was given an unlimited amount of candy free coupons to the candy company on May 23, 2010.
On this day, Dzx can choose any number of N products from the candy company to take home and enjoy.
Each of the N products of the candy company contains a different number of candies.
Dzx hopes that the total number of candies in the product he chooses is an integral multiple of K, so that he can evenly distribute the candies to his partners who help him maintain world peace.
Of course, on the basis of meeting this condition, the more the total number of candies, the better.
How many candies can Dzx take away at most?
Note: Dzx can only take away the entire product of the confectionery company.

The first line of the input format
contains two integers N and K.
In the following N lines, each line contains 1 integer, which means the number of candies contained in the product of the candy company, which does not exceed 1,000,000.

The output format
meets the requirements of the maximum number of candies that can be achieved. If the requirement of multiples of K cannot be reached, 0 is output.

Data range
1≤N≤100,
1≤K≤100,

Input sample:
5 7
1
2
3
4
5

Output sample:
14
sample explanation
Dzx's choice is 2+3+4+5=14, so the total number of candies is a multiple of 7, and it is the most total choice.

code show as below:

#include <iostream>
#include <cstring>
using namespace std;
const int N = 110;
int f[N][N];
int main()
{
    
    
    int n,k;
    cin>>n>>k;
    memset(f,-0x3f,sizeof(f));
    f[0][0] = 0;
    for (int i = 1;i<=n;i++)
    {
    
    
        int x;
        cin>>x;
        for (int j = 0;j<k;j++)
        {
    
    
            f[i][j] = max(f[i-1][j],f[i-1][((j-x)%k+k)%k]+x);
        }
    }
    cout<<f[n][0]<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_51955470/article/details/114109705