A turtle moves following by logos.(length is \(N\)) \(F\) means "move 1 unit forward", \(T\) means turned around(180°). You must change the order \(M\) times.(\(F\) -> \(T\) , \(T\) -> \(F\))
\(N \le 50, M \le 100\).
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define debug(...) fprintf(stderr,__VA_ARGS__)
#define Debug(x) cout<<#x<<"="<<x<<endl
using namespace std;
typedef long long LL;
const int INF=1e9+7;
inline LL read(){
register LL x=0,f=1;register char c=getchar();
while(c<48||c>57){if(c=='-')f=-1;c=getchar();}
while(c>=48&&c<=57)x=(x<<3)+(x<<1)+(c&15),c=getchar();
return f*x;
}
const int N = 1005;
int dp[N][N][2];
char s[N];
int n, m;
inline void chkmax(int& a, int b){ a = a > b ? a : b; }
int main(){
// freopen("a.in","r",stdin);
scanf("%s", (s + 1));
n = strlen(s + 1);
m = read();
memset(dp, 0xcf, sizeof dp);
dp[0][0][0] = dp[0][0][1] = 0;
for(int i = 1; i <= n; ++i){
for(int j = 0; j <= m; ++j){ // turned j times in total.
for(int k = 0; k <= j; ++k){ // turn k times at i.
if(s[i] == 'F'){
if(k & 1){
chkmax(dp[i][j][0], dp[i - 1][j - k][1]);
chkmax(dp[i][j][1], dp[i - 1][j - k][0]);
}
else{
chkmax(dp[i][j][0], dp[i - 1][j - k][0] + 1);
chkmax(dp[i][j][1], dp[i - 1][j - k][1] - 1);
}
}
if(s[i] == 'T'){
if(k & 1){
chkmax(dp[i][j][0], dp[i - 1][j - k][0] + 1);
chkmax(dp[i][j][1], dp[i - 1][j - k][1] - 1);
}
else{
chkmax(dp[i][j][0], dp[i - 1][j - k][1]);
chkmax(dp[i][j][1], dp[i - 1][j - k][0]);
}
}
}
// printf("dp[%d][%d] = %d, %d\n", i, j, dp[i][j][0], dp[i][j][1]);
}
}
printf("%d\n", max(dp[n][m][0], dp[n][m][1]));
}