---
# System prepended metadata

title: 磁軌移動序列
tags: [APCS, recursion]

---

題目連結：https://zerojudge.tw/ShowProblem?problemid=k733


```C++=
#include <bits/stdc++.h>

using namespace std;

string s;
int rights = 0;

// 一次 L 代表一次新的遞迴
// LV 紀錄一次第回中的最左邊；RV 則需要不斷更新
// 需要開 long long，不要忘記
long long int move(int &LV, int &RV, int layers){
    RV = -1;
    LV = -1;
    long long int ans = 0;
    while (rights<s.size()){
        if (s[rights] == 'T'){
            int steps = stoi(s.substr(rights+1,2));
            if (RV < 0) LV = steps;
            else{
                ans += abs(steps - RV);
            }
            RV = steps;
            rights += 3;
        }
        else if (s[rights] == 'L'){
            int loop_times = stoi(s.substr(rights+1,1));
            int L ,R;
            rights+=2;
            long long int cost = move(L,R, layers+1);
            
            if (RV>=0) ans += abs(L-RV);  // 這裡的判斷式很重要，因為左側邊界不一定每次都有東西
            else LV = L;
            RV = R;
            ans += loop_times*cost + abs(L-R)*(loop_times-1);
        }
        else if (s[rights] == 'E'){
            rights++;
            return ans;
        }
    }
    return ans;
    
}


int main()
{
    cin>>s;
    int left = 0, right = 0;
    long long int ans;
    ans = move(left,right, 0);
    cout<<ans;
    return 0;
}


// T10L2L3T15T22L2T15L5T19T45ET32ET23EET55L2T44T22E

```