DSA
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.2 KiB

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. const int maxn = (int) 3e5 + 1;
  5. int n, k;
  6. ll ans;
  7. int a[maxn], p, u[maxn];
  8. int main(){
  9. cin >> n >> k;
  10. for(int i = 0; i < n; i++){
  11. cin >> a[i];
  12. }
  13. p = n / 2;
  14. for(int i = 0; i < (1 << p); i++){
  15. ll res = 0;
  16. for(int j = 0; j < p; j++){
  17. if((i >> j) & 1){
  18. res += a[j];
  19. }
  20. }
  21. u[i] = res % k;
  22. ans = max(ans, res % k);
  23. }
  24. sort(u, u + (1 << p));
  25. n -= p;
  26. for(int i = 0; i < (1 << n); i++){
  27. ll res = 0;
  28. for(int j = 0; j < n; j++){
  29. if((i >> j) & 1){
  30. res += a[j + p];
  31. }
  32. }
  33. res %= k;
  34. ans = max(ans, res);
  35. int l = 0, r = (1 << p) - 1;
  36. while(r - l > 1){
  37. int mid = (l + r) / 2;
  38. if(u[mid] + res >= k){
  39. r = mid;
  40. }
  41. else {
  42. l = mid;
  43. }
  44. }
  45. int p1 = 0;
  46. if(u[l] + res >= k){
  47. p1 = l;
  48. }
  49. else {
  50. p1 = r;
  51. }
  52. ans = max(ans, (u[(1 << p) - 1] + res) % k);
  53. ans = max(ans, (u[p1 - 1] + res) % k);
  54. }
  55. cout << ans;
  56. }