Explanation
For this problem, we are given numbers and have to find a combination such that the sum of all elements in this combination modulo is maximized. A naive approach, i.e. trying out all possible combinations, is not feasible. However, we can use the Meet-In-The-Middle Technique to reduce the time complexity to , which would be enough for our time bound.
We first split the given array into two halves that are equally long. In case of odd , we just put one more element into the first half. Then, we generate all combinations of numbers in the first half by using a bit mask and save the results modulo in a sorted set. For the second half, let's also generate all combinations for them. For each of these combinations, the maximal sum is the sum of all elements in this combination, , plus the largest sum of a combination of the first half, , which is less than . It is never optimal to choose a value larger than since otherwise the result would be , which is strictly less than .
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;/*** Calculate the sum of all elements in arr, represented by the binary mask, and* take modulo mod.*/int unmask(int mask, const vector<int> &arr, int mod) {int current_sum = 0;for (int bit = 0; bit < arr.size(); bit++) {
Java
import java.io.*;import java.util.*;public class MaxSubseq {public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));StringTokenizer st = new StringTokenizer(br.readLine());int n = Integer.parseInt(st.nextToken());int m = Integer.parseInt(st.nextToken());
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!