1859E - Maximum Monogonosity - CodeForces Solution


brute force dp math

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#define int long long
#define ii pair<int, int>
#define fi first
#define se second
using namespace std;

const int MAXN = 2e5 + 6;
const int MOD = 1e9 + 7;

int signs[4][4] = {
    {1, 1, -1, -1}, {-1, 1, -1, 1}, {1, -1, 1, -1}, {-1, -1, 1, 1}};

int32_t main() {
  cin.tie(0)->sync_with_stdio(0);
  if (fopen("input.txt", "r")) {
    freopen("input.txt", "r", stdin);
  }

  int T = 1;
  cin >> T;
  while (T--) {
    int n, k;
    cin >> n >> k;
    vector<int> a(n + 1), b(n + 1);
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
    }
    for (int i = 1; i <= n; i++) {
      cin >> b[i];
    }
    vector<vector<int> > dp(n + 1, vector<int>(k + 1));
    vector<vector<int> > costs(max(n, k) + 1, vector<int>(4));

    for (int i = 1; i <= n; i++) {
      for (int j = 0; j < 4; j++) {
        auto [bl, br, al, ar] = signs[j];
        costs[i - 1][j] = al * a[i] + bl * b[i];
      }
    }

    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= min(i, k); j++) {
        dp[i][j] = dp[i - 1][j];
        for (int t = 0; t < 4; t++) {
          auto [bl, br, al, ar] = signs[t];
          dp[i][j] = max(dp[i][j], costs[i - j][t] + ar * a[i] + br * b[i]);
        }
        if (i == n) continue;
        for (int t = 0; t < 4; t++) {
          auto [bl, br, al, ar] = signs[t];
          costs[i - j][t] =
              max(costs[i - j][t], dp[i][j] + al * a[i + 1] + bl * b[i + 1]);
        }
      }
    }
    cout << dp[n][k] << "\n";
  }
  return 0;
}


Comments

Submit
0 Comments
More Questions

Number of triangles
AND path in a binary tree
Factorial equations
Removal of vertices
Happy segments
Cyclic shifts
Zoos
Build a graph
Almost correct bracket sequence
Count of integers
Differences of the permutations
Doctor's Secret
Back to School
I am Easy
Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word
Going to office
Color the boxes
Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship
Health of a person
Divisibility
A. Movement
Numbers in a matrix
Sequences
Split houses