题目链接:https://ac.nowcoder.com/acm/contest/70/E
题目大意:
略
分析:
DP或记忆化搜索,个人觉得记忆化搜索比较好做,逻辑清晰,代码量少
代码如下:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 #define rep(i,n) for (int i = 0; i < (n); ++i) 5 #define For(i,s,t) for (int i = (s); i <= (t); ++i) 6 #define rFor(i,t,s) for (int i = (t); i >= (s); --i) 7 #define foreach(i,c) for (__typeof(c.begin()) i = c.begin(); i != c.end(); ++i) 8 #define rforeach(i,c) for (__typeof(c.rbegin()) i = c.rbegin(); i != c.rend(); ++i) 9 10 #define pr(x) cout << #x << " = " << x << " " 11 #define prln(x) cout << #x << " = " << x << endl 12 13 #define LOWBIT(x) ((x)&(-x)) 14 15 #define ALL(x) x.begin(),x.end() 16 #define INS(x) inserter(x,x.begin()) 17 18 #define ms0(a) memset(a,0,sizeof(a)) 19 #define msI(a) memset(a,inf,sizeof(a)) 20 #define msM(a) memset(a,-1,sizeof(a)) 21 22 inline int gc(){ 23 static const int BUF = 1e7; 24 static char buf[BUF], *bg = buf + BUF, *ed = bg; 25 26 if(bg == ed) fread(bg = buf, 1, BUF, stdin); 27 return *bg++; 28 } 29 30 inline int ri(){ 31 int x = 0, f = 1, c = gc(); 32 for(; c<48||c>57; f = c=='-'?-1:f, c=gc()); 33 for(; c>47&&c<58; x = x*10 + c - 48, c=gc()); 34 return x*f; 35 } 36 37 typedef long long LL; 38 typedef unsigned long long uLL; 39 const double EPS = 1e-9; 40 const int inf = 1e9 + 9; 41 const LL mod = 1e9 + 7; 42 const int maxN = 1e5 + 7; 43 const LL ONE = 1; 44 45 46 int n, m, ans; 47 string c; 48 // dp[i][j][k][0/1]表示已进行了i次指令,已修改了j次指令,当前走到k位置,朝向为前(后)这种情况能否到达 49 // dp[i][j][k][0/1] = 1表示能到达,dp[i][j][k][0/1] = 0表示不能 50 // 为避免负数问题,k初始值为100 51 int dp[107][57][207][2]; 52 53 inline void dfs(int x, int y, int z, int d) { 54 if(x > m || y > n || dp[x][y][z][d]) return; 55 dp[x][y][z][d] = 1; 56 57 if(c[x] == 'F') { 58 // 修改 59 dfs(x + 1, y + 1, z, !d); 60 // 不修改 61 dfs(x + 1, y, z + (d ? -1 : 1), d); 62 } 63 if(c[x] == 'T') { 64 // 修改 65 dfs(x + 1, y + 1, z + (d ? -1 : 1), d); 66 // 不修改 67 dfs(x + 1, y, z, !d); 68 } 69 } 70 71 int main(){ 72 cin >> c >> n; 73 m = c.size(); 74 75 dfs(0, 0, 100, 0); 76 77 rep(k, 201) { 78 if(dp[m][n][k][0] || dp[m][n][k][1]) ans = max(ans, abs(k - 100)); 79 } 80 81 cout << ans << endl; 82 return 0; 83 }