A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward").
You are given a list of commands that will be given to the turtle. You have to change exactly n commands from the list (one command can be changed several times). How far from the starting point can the turtle move after it follows all the commands of the modified list?
The first line of input contains a string commands — the original list of commands. The string commands contains between 1 and 100 characters, inclusive, and contains only characters "T" and "F".
The second line contains an integer n (1 ≤ n ≤ 50) — the number of commands you have to change in the list.
Output the maximum distance from the starting point to the ending point of the turtle's path. The ending point of the turtle's path is turtle's coordinate after it follows all the commands of the modified list.
FT 1
2
FFFTFFF 2
6
In the first example the best option is to change the second command ("T") to "F" — this way the turtle will cover a distance of 2 units.
In the second example you have to change two commands. One of the ways to cover maximal distance of 6 units is to change the fourth command and first or last one.
当n>=T时结果是 length-(n-T)%2 而n<T的时候就比较复杂。
找一个n个修改后变换后长的序列。一个t就是*-1 一个F就是+1 不过这个只能用来仿真,并不是看到问题的本质啊。越长t的代价就越大。一条主序列,减去一头一尾的长度,类似的一种方式,这是计算思维吗。。。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
char str[110];
int n, m;
bool dp[110][210][2][55];
int main()
{
while (cin >> str >> m)
{
memset(dp, 0, sizeof(dp));
n = strlen(str);
dp[0][100][0][0] = 1;
for (int i=0;i<n;i++)
for (int j=0;j<=200;j++)
for (int d=0;d<2;d++)
for (int k=0;k<=m;k++)
if (dp[i][j][d][k])
{
if (str[i] == 'F')
{
int dd = (d == 0) ? 1 : -1;
dp[i+1][j+dd][d][k] = 1;
dp[i+1][j][1-d][k+1] = 1;
}
else
{
int dd = (d == 0) ? 1 : -1;
dp[i+1][j][1-d][k] = 1;
dp[i+1][j+dd][d][k+1] = 1;
}
}
int ans = 0;
for (int i=0;i<=200;i++)
for (int j=0;j<2;j++)
for (int k=m;k>=0;k-=2)
if (dp[n][i][j][k])
ans = max(ans, abs(i-100));
cout << ans << endl;
}
return 0;
}