I was trying to solve this simple DP question 219C - Color Stripe and my solution is working well in the text editor for C++ 17 , but it gives WA on sample cases here.. Please help. Code:-
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define vi(x) vector<x>
#define all(x) x.begin(),x.end()
#define pii pair<int,int>
#define vpii vector< pair<int,int> >
#define mii map<int,int>
#define MOD 1000000007
using namespace std;
typedef long long ll;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n,k;
cin>>n>>k;
string s;
cin>>s;
int dp[n][k];
for(int i=0;i<n;i++)
for(int j=0;j<k;j++)
dp[i][j]=MOD;
string dps[n][k];
for(int i=0;i<k;i++)
{
dp[0][i]=1;
dps[0][i]+=('A'+i);
}
dp[0][s[0]-'A']=0;
for(int i=1;i<n;i++)
{
for(int j=0;j<k;j++)
{
int in=-1;
for(int l=0;l<k;l++)
{
if(l!=j)
{
if(dp[i][j]>dp[i-1][l])
{
dp[i][j]=dp[i-1][l];
in=l;
}
}
}
int x=s[i]-'A';
if(j!=x)
dp[i][j]++;
string t;
t+=('A'+j);
dps[i][j]=dps[i-1][in]+t;
}
}
int ans=MOD,in=-1;
for(int i=0;i<n;i++)
{
if(ans>dp[n-1][i])
{
ans=min(ans,dp[n-1][i]);
in=i;
}
}
cout<<ans<<endl;
cout<<dps[n-1][in]<<endl;
return 0;
}
I guess you don't use sanitizers when you compile, so that is why you didn't notice the index out of bounds error on line 55. Here's what I got when running your program on my machine: "SUMMARY: AddressSanitizer: dynamic-stack-buffer-overflow C.cpp:55 in main" In the code:
ans > dp[n - 1][i]
In my opinion, it is always worth it to compile without optimizations and with -g and with warning flags (-Wall, -Wextra, -Wshadow) and with sanitizers (address sanitizer and undefined behavior sanitizer) and the -D_GLIBCXX_DEBUG flag. On my machine, compiling takes only 1 second even with all these flags. Yes the runtime will be slower, but if you need to test runtime speed, then simply compile with optimizations (-O2) and without the other flags.