CodeForces 132C Logo Turtle (记忆化搜索)

Description

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?

Input

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

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.

Sample Input

Input
FT 1
Output
2
Input
FFFTFFF 2
Output
6

Hint

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.

题解:给一个序列,有TF,F代表机器人向前走一步,T代表机器人转身,再给你一个N问改变N个字母后机器人最多可以走多远,每个字母可以改变多次;刚开始写了下没用记忆化搜索果断超时了,而且还不知道怎么把一个字母改变多次,然后看了下大神的写法,加个数组记忆下就好了,关于字母可以改变多次,直接循环N,N-=2就好了;

dp[2][MAXN<<1][MAXN][50],MAXN<<1是因为当前位置可能为负数;

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
const int INF=0x3f3f3f3f;
#define SI(x) scanf("%d",&x)
#define PI(x) printf("%d",x)
#define P_ printf(" ")
#define mem(x,y) memset(x,y,sizeof(x))
const int MAXN=110;
char s[MAXN];
int dp[2][MAXN<<1][MAXN][52];
int dfs(int fw,int pos,int l,int n){
    if(n<0)return 0;
    if(!s[pos])
        return n>0?0:abs(l);
    if(dp[fw][l+100][pos][n]!=-1)return dp[fw][l+100][pos][n];
    return dp[fw][l+100][pos][n]=max(dfs(fw,pos+1,fw?l+1:l-1,n-(s[pos]=='T')),dfs(1-fw,pos+1,l,n-(s[pos]=='F')));
}
int main(){
    int n;
    while(~scanf("%s",s)){
        SI(n);
        mem(dp,-1);
        int ans=0;
        for(;n>=0;n-=2)ans=max(ans,dfs(1,0,0,n));
        printf("%d\n",ans);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值