1

Here is the code in C++ with scanf/printf. I ran it with file I/O but cin/cout on my laptop as well as command-line cin/cout. Both worked fine. The USACO grader did not work with these two either. scanf/printf does not work either. (please help, i know this will probably be a dumb mistake).

#include <cstdio>
#include <cassert>
#include <algorithm>

using namespace std;
using ll = long long;

int main(){
    int n, k;
    scanf("%d", &n);
    scanf("%d", &k);
    char s[10];

    int gestures[n+1], dp[n+1][k+1][3];
    for (int i = 1; i <= n; i++){
        scanf("%s", s);
        if (s[0]=='H') gestures[i] = 0;
        else if (s[0]=='P') gestures[i] = 1;
        else gestures[i] = 2;
    }
    int res = 0;
    for (int i = 1; i <= n; i++){
        for (int s = 0; s <= k; s++){
            for (int p1 = 0; p1 < 3; p1++){
                if (n){
                    dp[i][s][p1] = max(dp[i-1][s-1][(p1+1)%3], dp[i][s][p1]);
                    dp[i][s][p1] = max(dp[i-1][s-1][(p1+2)%3], dp[i][s][p1]);
                }
                dp[i][s][p1] = max(dp[i-1][s][p1], dp[i][s][p1]);
                dp[i][s][p1] += (p1==gestures[i]);
                if (i==n) res = max(res, dp[i][s][p1]);
            }
        }
    }
    printf("%d\n", res);
}
  • 1
    Ask yourself, where in my code do I set the values of `dp` to anything before I use them in a calculation. – NathanOliver Sep 09 '21 at 04:15
  • In the very first iteration of the `for (int s = 0; s <= k; s++)` loop, is `n` guaranteed to always be non-zero? Otherwise you will use `-1` as index, which of course leads to *undefined behavior* as it's out of bounds. – Some programmer dude Sep 09 '21 at 04:18
  • On another couple of notes, while you have avoided some of the traps common on so-called "competition" or "online judge" sites, you do fall into others. Like the `ll` type alias which is bad habit. As is [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). You also lack comments, use simple one-letter variable names without description, and try to cram multiple statements on a single line (which makes the code harder to read, understand and maintain). And have no buffer-overflow protection. – Some programmer dude Sep 09 '21 at 04:22
  • 1
    *Here is the code in C++* -- `int gestures[n+1], dp[n+1][k+1][3];` -- None of this is valid C++. C++ requires that arrays have compile-time constant expressions to denote the number of elements, not runtime values such as `n+1`, `k+1`, etc. In C++, `std::vector` is used as the dynamic array. The second thing is that even if that syntax is allowed, those arrays could easily exhaust the stack memory if `n` or `k` are large enough. Instead of copying code you see from those "online judge" sites, learn proper C++. Also `int64_t` instead of `ll`. – PaulMcKenzie Sep 09 '21 at 04:25

0 Answers0