Problem:
E: 卒業式
背景
ある日 Y さんはプログラミングコンテストに参加するため，会場がある大学に向かいました．
ところが大学に着くと人がたくさん！なんと今日は卒業式だったのです．
会場に向かおうにも人に押し流されてしまい，自分の進みたい方向に進むことすらできません．
人混みから抜け出すために，Y さんは今いる場所から少しでも遠くに行きたいと考えました．
そこで Y さんは状況を以下のような問題として定式化し，競技プログラミングを役に立てることにしました．
なお，以下の問題文では Y さんは点 $P$ としてモデル化されています．
問題
座標平面上の原点に点 $P$ が置かれている．
点 $P$ を動かし，できるだけ原点からのマンハッタン距離が遠い位置に移動させたい．
はじめに，文字列 $S = s_1s_2 \cdots s_{|S|}$ ($|S|$ は $S$ の文字数) が与えられる．
点 $P$ の移動は，文字列 $S$ の先頭から文字を 1 文字ずつ読み込むことで行う．
文字列 $S$ は文字 'U', 'L', 'D', 'R' からなる．
それぞれの文字を読み込んだとき，点 $P$ の移動前の座標を $(x, y)$ とすると，
移動後の点 $P$ の座標はそれぞれ $(x, y+1),\ (x-1, y),\ (x, y-1),\ (x+1, y)$ となる．
各文字を読み込む直前に，魔法をかけるか否かを選択することができる．
魔法には魔法 1 と魔法 2 の二種類がある．文字列 $S$ の $i$ 番目の文字を $s_i$ とすると，
$s_i$ を読み込む直前に魔法をかけたときの変化は以下の通りである．
魔法 1 をかけたとき: 全ての $s_j \ (i \le j \le |S|)$ に対し，'U' を 'D' に，'D' を 'U' に置換する．
魔法 2 をかけたとき: 全ての $s_j \ (i \le j \le |S|)$ に対し，'L' を 'R' に，'R' を 'L' に置換する．
直感的には，魔法 1 ではその後の上下の扱いを反転させることができ，魔法 2 では左右の扱いを反転させることができる．
ある文字を読み込む前にかける魔法の回数は複数回でも構わない．また，両方の魔法を続けてかけてもかまわない．
ただし，文字列 $S$ の文字をすべて読み終えるまでに魔法をかけられる回数は，合計 $K$ 回までである．
詳細はサンプルを参照されたい．
文字列 $S$ の文字をすべて読み終えた後の点 $P$ の座標を $(x',y')$  とするとき，$|x'| + |y'|$ 
の最大値を求めよ．
制約
$1 \le |S| \le 2000$
$1 \le K \le 2000$
入力
入力は以下の形式で標準入力から与えられる．
$S$
$K$
出力
$|x'| + |y'|$ の最大値を 1 行で出力せよ．また、末尾に改行も出力せよ.
サンプル
サンプル入力 1
RRLUDDD
2
サンプル出力 1
7
3 文字目を読み込む直前に魔法 2 をかけると，文字列 $S$ は "RRRUDDD" となる．
続いて 5 文字目を読み込む直前に魔法 1 をかけると，文字列 $S$ は "RRRUUUU" となる．
すべての文字を読み終えた後の点 $P$ の座標は $(3, 4)$ となり，
原点からのマンハッタン距離は 7 である．これはこの例の最大値である．
サンプル入力 2
LULLLUULLU
1984
サンプル出力 2
10
1 回も魔法をかけなかった場合，$x’ = -6, \ y’ = 4$ となり，$|x’| + |y’| = 10$ である．
サンプル入力 3
DRDLUDD
1
サンプル出力 3
5
サンプル入力 4
LURRRLUDLL
1
サンプル出力 4
6

Submitted solutions:

code_snippet: #include<bits/stdc++.h>
using namespace std;

typedef long long ll;

#define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++)
#define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--)

template <typename T> bool chmin(T &a, const T &b) {
	if (a <= b) return false;
	a = b;
	return true;
}

template <typename T> bool chmax(T &a, const T &b) {
	if (a >= b) return false;
	a = b;
	return true;
}

template <typename T> T max(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmax(ret, a[i]);
	return ret;
}

template <typename T> T min(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmin(ret, a[i]);
	return ret;
}

template <typename T> T sum(vector<T> &a){
	T ret = 0;
	for (int i=0; i<(int)a.size(); i++) ret += a[i];
	return ret;
}

vector<int> solve(vector<int> a){
	int geta = 2500;
	vector<int> dp0(5000,2100);
	vector<int> dp1(5000,2100);
	dp0[geta] = 0;
	rep(i,0,(int)a.size()){
		vector<int> ndp0(5000,2100);
		vector<int> ndp1(5000,2100);
		rep(j,0,5000){
			if (0 <= j+a[i] && j+a[i] < 5000){
				chmin(ndp0[j+a[i]], dp0[j]);
				chmin(ndp0[j+a[i]], dp1[j] + 1);
			}
			if (0 <= j-a[i] && j-a[i] < 5000){
				chmin(ndp1[j-a[i]], dp1[j]);
				chmin(ndp1[j-a[i]], dp0[j] + 1);
			}
		}
		swap(ndp0, dp0);
		swap(ndp1, dp1);
	}
	vector<int> targ(2200, 0);
	rep(j,0,5000){
		chmax(targ[dp0[j]], abs(j-geta));
		chmax(targ[dp1[j]], abs(j-geta));
	}
	rep(j,0,2180){
		chmax(targ[j+1], targ[j]);
	}
	return targ;
}


int main(){
	string s; cin >> s;
	int k; cin >> k;

	vector<int> a, b;
	rep(i,0,(int)s.size()){
		if (s[i] == 'U') a.push_back(+1);
		if (s[i] == 'D') a.push_back(-1);
		if (s[i] == 'L') b.push_back(+1);
		if (s[i] == 'R') b.push_back(-1);
	}

	vector<int> x = solve(a);
	vector<int> y = solve(b);
	
	int ans = 0;
	rep(i,0,k+1){
		chmax(ans, x[i] + y[k-i]);
	}
	cout << ans << '\n';
}
accuracy: 1
time_ms: 20
memory_kb: 3544
final_rank: 2

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
#define rep(i,n) for(ll i=0;i<(n);++i)
#define ALL(x) x.begin(),x.end()
#define BACK(x) x.rbegin(),x.rend()
#define MOD1 1000000007
#define MOD2 998244353
#define MOD1_BASE 131
#define INF (LLONG_MAX / 2)
#define FLOAT_ANS setprecision(30)
#define TORAD(x) (x*acos(-1)/180.0)
#define TODEG(x) (x*180/acos(-1))
#define GET_VALUENAME(value) # value

using namespace std;
using ll = long long;
using LL = __int128_t;
using ull = unsigned long long;

template<typename T> // T:重み
using p_que = priority_queue<T,vector<T>,greater<T>>;

template<typename T>
bool chmin(T& a,T b){if(a>b){a=b;return true;}return false;}

template<typename T>
bool chmax(T& a,T b){if(a<b){a=b;return true;}return false;}

ll modpow(ll a, ll n, ll mod) {ll res=1;while (n>0) {if(n&1)res=(res*(a%mod))%mod;a=((a%mod)*(a%mod))%mod;n>>=1;}return res;}

template<typename T>
void RotateVec2(vector<vector<T>>&v){ll h=v.size();ll w=v[0].size();vector<vector<T>>t(w,vector<T>(h));rep(i,h){rep(j,w){t[j][h-i-1]=v[i][j];}}v=t;}

template<class T>
bool InRange(T x, T mn, T mx){return (mn <= x && x <= mx);}

template<typename T>
vector<T>&merged(vector<T>&a,vector<T>&b) {vector<T>res;merge(a.begin(),a.end(),b.begin(),b.end(),back_inserter(res));return res;}

struct UnionFind{
    vector<ll>tree;
    UnionFind(ll x):tree(x, -1){}
    ll root(ll x){if(tree[x]<0) return x;return tree[x]=root(tree[x]);}
    bool same(ll x,ll y){return root(x)==root(y);}
    ll size(ll x){return -tree[root(x)];}
    void unite(ll x,ll y){x=root(x),y=root(y);if(x==y)return;if(size(x)<size(y))swap(x,y);tree[x]+=tree[y];tree[y]=x;}
};

template<class T>
struct SegTree{
    ll n;T e;vector<T>tree,lazy;function<T(T,T)>f,add;
    SegTree(ll n_,function<T(T,T)>f_,T e_=0,function<T(T,T)>add_=[](T next,T old){return next;}):e(e_),f(f_),add(add_){
        ll x=1;
        while(x<n_)x*=2;
        n=x;
        tree.assign(n*2,e);
        lazy.assign(n*2,e);
    }
    void eval(T k) {
        if (lazy[k] == e) return;
        if (k < n-1){
            lazy[k*2+1]=lazy[k*2+1]=lazy[k];
        }
        tree[k]=lazy[k], lazy[k]=e;
    }
    void update(ll idx,T x){
        update(idx, idx+1, x);
    }
    void update(ll a, ll b, ll x) { update(a, b, x, 0, n, 0); }
    void update(ll a, ll b, ll x, ll l, ll r, ll k) {
        eval(k);
        if (a <= l and r <= b) {
            lazy[k] = x;
            eval(k);
        }
        else if (a < r and l < b) {
            update(a, b, x, l, (l+r)/2, k*2+1);
            update(a, b, x, (l+r)/2, r, k*2+1);
            tree[k] = f(tree[k*2+1], tree[k*2+2]);
        }
    }
    T query(ll x,ll y){
        return query_sub(x,y,0,n,0);
    }
    T query_sub(ll x,ll y,ll l,ll r,ll k){
        eval(k);
        if(r<=x||y<=l)return e;
        if(x<=l&&r<=y)return tree[k];
        T c1=query_sub(x,y,l,(l+r)/2,k*2+1);
        T c2=query_sub(x,y,(l+r)/2,r,k*2+2);
        return f(c1,c2);
    }
    T get(ll idx){return tree[idx+n-1];}
};

template<std::uint_fast64_t Modulus> class modint {
    using u64 = std::uint_fast64_t;
public:
    u64 a;
    constexpr modint(const u64 x = 0) noexcept : a(((x % Modulus)+Modulus)%Modulus) {}
    constexpr u64 &value() noexcept { return a; }
    constexpr const u64 &value() const noexcept { return a; }
    constexpr modint operator+(const modint rhs) const noexcept {return modint(*this) += rhs;}
    constexpr modint operator-(const modint rhs) const noexcept {return modint(*this) -= rhs;}
    constexpr modint operator*(const modint rhs) const noexcept {return modint(*this) *= rhs;}
    constexpr modint operator/(const modint rhs) const noexcept {return modint(*this) /= rhs;}
    constexpr modint &operator+=(const modint rhs) noexcept {a += rhs.a;if (a >= Modulus) {a -= Modulus;}return *this;}
    constexpr modint &operator-=(const modint rhs) noexcept {if (a < rhs.a) {a += Modulus;}a -= rhs.a;return *this;}
    constexpr modint &operator*=(const modint rhs) noexcept {a = a * rhs.a % Modulus;return *this;}
    constexpr modint &operator/=(modint rhs) noexcept {
        u64 exp = Modulus - 2;
        while (exp) {
            if (exp % 2) {
                *this *= rhs;
            }
            rhs *= rhs;
            exp /= 2;
        }
        return *this;
    }
    constexpr modint &operator=(u64 x){ a = x % Modulus; return *this; }
};

template<class T=ll>
struct Vector2D {
    T x, y;
    Vector2D():x(0),y(0) {}
    Vector2D(T x_, T y_):x(x_),y(y_) {}

    double length() const { return sqrt((double)x*x+y*y); };
    T lengthp() const { return x*x+y*y; };
    bool inrange(const Vector2D a, const Vector2D b) { return (InRange(x, a.x, b.x) and InRange(y, a.y, b.y)); }
    Vector2D yx() { return Vector2D{ y, x }; }
    Vector2D operator-(const Vector2D a) const { return Vector2D(*this) -= a; }
    Vector2D operator+(const Vector2D a) const { return Vector2D(*this) += a; }
    T operator*(const Vector2D a) const { return x*a.x+y*a.y; }
    Vector2D operator*(const T a) const { return Vector2D(*this) *= a; }
    Vector2D operator/(const T a) const { return Vector2D(*this) /= a; }
    Vector2D &operator+=(const Vector2D a) { x += a.x; y += a.y; return *this; }
    Vector2D &operator-=(const Vector2D a) { x -= a.x; y -= a.y; return *this; }
    Vector2D &operator-=(const T a) { x -= a; y -= a; return *this; }
    Vector2D &operator*=(const T a) { x *= a; y *= a; return *this; }
    Vector2D &operator/=(const T a) { x /= a; y /= a; return *this; }
    friend ostream& operator<< (ostream& stream, const Vector2D<>& x);
    bool operator==(const Vector2D a) const { return (x==a.x and y==a.y); }
    bool operator!=(const Vector2D a) const { return not (x==a.x and y==a.y); }
    bool operator>(const Vector2D a) const { return a < *this; }
    bool operator<(const Vector2D a) const 
    {
        return make_pair(x,y) < make_pair(a.x, a.y);
        // return x*a.y < y*a.x;
    }
};

ostream& operator<< (ostream& stream, const Vector2D<ll>& x) {
    string s = "(" + to_string(x.x) + ", " + to_string(x.y) + ")";
    stream << s;
    return stream;
}

ll popcount(ll x) { ll res = 0; while(x) {res+=x%2;x>>=1;} return res; }

// debug kit
void print() { cout << endl; }
template<class T>
void print_(vector<T>x) { for(auto i : x) cout << i << " "; }
template<class T>
void print_(T x) { cout << x << " "; }
#ifdef ONLINE_JUDGE 
template<class T, class ...Args>
void print(T head, Args... args) {}
template<class T>
void debug(T value) {}
#else
template<class T, class ...Args>
void print(T head, Args... args) { print_(head); print(args...); }
template<class T>
void debug(T value) { print((string)"\""+GET_VALUENAME(value)+"\": ", value); }
#endif

// MAIN PROGRAM ------------

using mint = modint<MOD2>;
using Vec2 = Vector2D<ll>;
const Vec2 Angle[] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};

struct State
{
    Vec2 pos = {0, 0};
    ll dist = -INF;
    int getDist() {
        return abs(pos.x) + abs(pos.y);
    }
    bool operator<(const State a) 
    {
        return dist < a.dist;
    }
};

int main() {
    string s;
    cin >> s;
    ll k, n = s.length();
    cin >> k;
    map<char, ll>mp;
    mp['U'] = 0;
    mp['L'] = 1;
    mp['D'] = 2;
    mp['R'] = 3;
    
    vector dp(k+10, vector(4, State{}));
    vector dp_next(k+10, vector(4, State{}));

    dp[0][0].dist = 0;

    rep(i, n) 
    {
        rep(j, k+1) rep(l, 4)
        {
            if (dp[j][l].dist == -INF) continue;
            int angle = mp[s[i]];
            if ((angle%2 and l/2) or (angle%2==0 and l%2)) angle = (angle+2)%4;

            State base = dp[j][l];
            rep(idx, 2)
            {
                // 0: 魔法なし, 1: 魔法あり
                State next = base;

                next.pos += Angle[angle];
                next.dist = next.getDist();

                chmax(dp_next[j+idx][l], next);

                // 魔法処理
                angle = (angle+2) % 4;
                if (angle % 2) l ^= 2;
                else l^= 1;
            }
        }
        dp = dp_next;
        dp_next = vector(k+10, vector(4, State{}));
    }

    ll ans = 0;
    rep(i, k+1){
        rep(j, 4) {
            chmax(ans, dp[i][j].dist);
        }
    }

    cout << ans << endl;
}
accuracy: 1
time_ms: 180
memory_kb: 4120
final_rank: 12

code_snippet: #line 2 "/Users/noya2/Desktop/Noya2_library/template/template.hpp"
using namespace std;

#include<bits/stdc++.h>
#line 1 "/Users/noya2/Desktop/Noya2_library/template/inout_old.hpp"
namespace noya2 {

template <typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &p){
    os << p.first << " " << p.second;
    return os;
}
template <typename T, typename U>
istream &operator>>(istream &is, pair<T, U> &p){
    is >> p.first >> p.second;
    return is;
}

template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v){
    int s = (int)v.size();
    for (int i = 0; i < s; i++) os << (i ? " " : "") << v[i];
    return os;
}
template <typename T>
istream &operator>>(istream &is, vector<T> &v){
    for (auto &x : v) is >> x;
    return is;
}

void in() {}
template <typename T, class... U>
void in(T &t, U &...u){
    cin >> t;
    in(u...);
}

void out() { cout << "\n"; }
template <typename T, class... U, char sep = ' '>
void out(const T &t, const U &...u){
    cout << t;
    if (sizeof...(u)) cout << sep;
    out(u...);
}

template<typename T>
void out(const vector<vector<T>> &vv){
    int s = (int)vv.size();
    for (int i = 0; i < s; i++) out(vv[i]);
}

struct IoSetup {
    IoSetup(){
        cin.tie(nullptr);
        ios::sync_with_stdio(false);
        cout << fixed << setprecision(15);
        cerr << fixed << setprecision(7);
    }
} iosetup_noya2;

} // namespace noya2
#line 1 "/Users/noya2/Desktop/Noya2_library/template/const.hpp"
namespace noya2{

const int iinf = 1'000'000'007;
const long long linf = 2'000'000'000'000'000'000LL;
const long long mod998 =  998244353;
const long long mod107 = 1000000007;
const long double pi = 3.14159265358979323;
const vector<int> dx = {0,1,0,-1,1,1,-1,-1};
const vector<int> dy = {1,0,-1,0,1,-1,-1,1};
const string ALP = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string alp = "abcdefghijklmnopqrstuvwxyz";
const string NUM = "0123456789";

void yes(){ cout << "Yes\n"; }
void no(){ cout << "No\n"; }
void YES(){ cout << "YES\n"; }
void NO(){ cout << "NO\n"; }
void yn(bool t){ t ? yes() : no(); }
void YN(bool t){ t ? YES() : NO(); }

} // namespace noya2
#line 1 "/Users/noya2/Desktop/Noya2_library/template/utils.hpp"
namespace noya2{

unsigned long long inner_binary_gcd(unsigned long long a, unsigned long long b){
    if (a == 0 || b == 0) return a + b;
    int n = __builtin_ctzll(a); a >>= n;
    int m = __builtin_ctzll(b); b >>= m;
    while (a != b) {
        int mm = __builtin_ctzll(a - b);
        bool f = a > b;
        unsigned long long c = f ? a : b;
        b = f ? b : a;
        a = (c - b) >> mm;
    }
    return a << min(n, m);
}

template<typename T> T gcd_fast(T a, T b){ return static_cast<T>(inner_binary_gcd(abs(a),abs(b))); }

long long sqrt_fast(long long n) {
    if (n <= 0) return 0;
    long long x = sqrt(n);
    while ((x + 1) * (x + 1) <= n) x++;
    while (x * x > n) x--;
    return x;
}

template<typename T> T floor_div(const T n, const T d) {
    assert(d != 0);
    return n / d - static_cast<T>((n ^ d) < 0 && n % d != 0);
}

template<typename T> T ceil_div(const T n, const T d) {
    assert(d != 0);
    return n / d + static_cast<T>((n ^ d) >= 0 && n % d != 0);
}

template<typename T> void uniq(vector<T> &v){
    sort(v.begin(),v.end());
    v.erase(unique(v.begin(),v.end()),v.end());
}

template <typename T, typename U> inline bool chmin(T &x, U y) { return (y < x) ? (x = y, true) : false; }

template <typename T, typename U> inline bool chmax(T &x, U y) { return (x < y) ? (x = y, true) : false; }

template<typename T> inline bool range(T l, T x, T r){ return l <= x && x < r; }

} // namespace noya2
#line 8 "/Users/noya2/Desktop/Noya2_library/template/template.hpp"

#define rep(i,n) for (int i = 0; i < (int)(n); i++)
#define repp(i,m,n) for (int i = (m); i < (int)(n); i++)
#define reb(i,n) for (int i = (int)(n-1); i >= 0; i--)
#define all(v) (v).begin(),(v).end()

using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using pil = pair<int,ll>;
using pli = pair<ll,int>;

namespace noya2{

/*　~ (. _________ . /)　*/

}

using namespace noya2;


#line 2 "c.cpp"

pair<vector<int>,vector<int>> calc(vector<int> rui, int k){
    int n = rui.size()-1;
    vector<int> dpma(k+1,-iinf), dpmi(k+1,iinf);
    dpma[0] = rui[0], dpmi[0] = rui[0];
    rep(i,n){
        auto epma = dpma, epmi = dpmi;
        rep(j,k){
            chmax(epma[j+1],dpma[j] + 2*rui[i]*(j % 2 == 0 ? -1 : 1));
            chmin(epmi[j+1],dpmi[j] + 2*rui[i]*(j % 2 == 0 ? -1 : 1));
        }
        swap(dpma,epma);
        swap(dpmi,epmi);
    }
    rep(i,k){
        chmax(dpma[i+1],dpma[i]);
        chmin(dpmi[i+1],dpmi[i]);
    }
    return pair(dpma,dpmi);
}

void solve(){
    string s; in(s);
    int k; in(k);
    int n = s.size();
    vector<int> ruix(n+1,0), ruiy(n+1,0);
    reb(i,n){
        ruix[i] = ruix[i+1] + (s[i] == 'D' ? 1 : s[i] == 'U' ? -1 : 0);
        ruiy[i] = ruiy[i+1] + (s[i] == 'R' ? 1 : s[i] == 'L' ? -1 : 0);
    }
    auto [xma, xmi] = calc(ruix,k);
    auto [yma, ymi] = calc(ruiy,k);
    int ans = 0;
    rep(i,k+1){
        chmax(ans,abs(xma[i])+abs(yma[k-i]));
        chmax(ans,abs(xma[i])+abs(ymi[k-i]));
        chmax(ans,abs(xmi[i])+abs(yma[k-i]));
        chmax(ans,abs(xmi[i])+abs(ymi[k-i]));
    }
    out(ans);
}

int main(){
    int t = 1; //in(t);
    while (t--) { solve(); }
}
accuracy: 1
time_ms: 10
memory_kb: 3460
final_rank: 1

code_snippet: //#define _GLIBCXX_DEBUG
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
//using uLL = unsigned __int128;
using str = string;
template <typename T> 
using pqg = priority_queue<T, vector<T>, greater<T>>;
template <typename T>
using pq = priority_queue<T>;
template <typename T>
using vec = vector<T>;
using pll = pair<long long, long long>;
using pii = pair<int, int>;
using vvvl = vector<vector<vector<ll>>>;
using vvl = vector<vector<ll>>;
using vp = vector<pair<ll, ll>>;
using vi = vector<int>;
using vl = vector<ll>;
#define vvvm  vector<vector<vector<mint>>>
#define vvm  vector<vector<mint>>
#define vm  vector<mint>
template <typename T1, typename T2>
using umap = unordered_map<T1, T2>;
template <typename T>
using uset = unordered_set<T>;
#define rep(i, s, f) for(long long i = s; i <= f; i++)
#define rep1(i, s, f) for(long long i = s; i <= f; i++)
#define per(i, s, f) for(long long i = s; i >= f; i--)
#define per1(i, s, f) for(long long i = s; i >= f; i--)
#define eb(a) emplace_back(a)
#define pb(a) push_back(a)
#define all0(x) (x).begin() ,(x).end()
#define all(x) (x).begin() + 1, (x).end()
#define ins(x, l, r) (l <= x && x <= r)
#define ENDL '\n'
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//これが本当の組み込み関数ってね（笑）
template <typename T>
int LB(vector<T> &A, T x) {
    return lower_bound(A.begin(), A.end(), x) - A.begin();
}

template <typename T>
int UB(vector<T> &A, T x) {
    return upper_bound(A.begin(), A.end(), x) - A.begin();
}
template <typename T>
void UNIQUE(vector<T> &A, int indexed) {
    sort(A.begin() + indexed, A.end());
    A.erase(unique(A.begin() + indexed, A.end()), A.end());
}

template <typename T>
vector<T> erase(vector<T>& A, T& x) {
	vector<T> res;
	for(T a : A) if(a != x) res.emplace_back(a);
	return res;
}
string split(string& S, int l, int r) {
	return S.substr(l, r - l + 1);
}

int msb(long long a) {
    if(a == 0) return -1;
    return 64 - int(__builtin_clzll(a));
}
template<class T>
void chmin(T &a, T b) {
    if(a > b) a = b;
}
template<class T>
void chmax(T &a, T b) {
    if(a < b) a = b;
}
//////////////////////////////////////////////////////////////////////
//数学系
///////////////////////////////////////////////////////////////////////
ll extgcd (ll a, ll b,  ll &x, ll &y) {
    if(b == 0) { x = 1;y = 0;return a;}
    ll d = extgcd(b, a%b, y, x);
    y -= a/b * x;
    return d;
}
template <typename T>
T CEIL(T a, T b) {
    assert(b != 0);
    if(a % b == 0) return a / b;
    if((a <= 0 && b < 0) || (a >= 0 && b > 0)) return a/b + 1;
    else return a / b;
}
template <typename T>
T FLOOR(T a, T b) {
    assert(b != 0);
    if(a % b == 0) return a / b;
    if((a <= 0 && b < 0) || (a >= 0 && b > 0)) return a/b;
    else return a/b - 1;
}
ll SQRT(ll a) {
    ll l = 0;
    ll r = 3037000499LL;
    while(l < r) {
        ll mid = (l + r + 1) / 2;
        if(mid * mid <= a) l = mid;
        else r = mid - 1;
    }
    return l;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//グローバル変数を置くところ
//#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC optimize "trapv" //お祈り。変数同士の演算でのみ感知。代入や、 a *= 10000 では感知しない。
const ll big = 1001001001;
const ll BIG = 2002002002002002002LL;
const double pi = 3.141592653589793;
vl dx{0, 1, 0, -1, 0, 1, 1, -1, -1};  // 座標平面において、(番兵) → ↓ ← ↑  ※ 右から時計回り 注 : グリッド or 座標で上下は反転する。
vl dy{0, 0, -1, 0, 1, 1, -1, -1, 1};
//const ll mod = 1000000007;
//const ll mod = 998244353;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
以降全てをswapする。

マンハッタン距離、つまり abs(x) + abs(y)の最大化。
K回まで操作をswapして良い（上下・左右で別の操作をする必要がある。)


[1]swapの分け方を全探索
これをすると、xとyを独立に考えてよくなる？（互いの操作で変化しない && スコアが独立)

「 t回まで操作をして良い時、abs(x)を最大化せよ。」
を解く。
最終的な座標の+-で場合分けすればよい。
あとは貪欲で終わり?

dpを事前にしておく。

dpy[2][f][i][d] .... iまで見た。d回上下のswapをした。今の状態がfの時の、yの最小値・最大値。
dpx[2][f][i][d] .... iまで、d回横、今の状態がf, xのmin/max

iを飛ばす。
dp[2][f][k]
min/max,  flag, k回使った。
O(KN)


LRLRLLLRLRLRLLRRR

計算量を見積もる。
分け方でK通り。
分け方が決まった時、+-で2通り。

*/

void solve() {
	string S;
	cin >> S;
	ll K;
	cin >> K;
	ll N = S.size();
	S = " " + S;

	vvvl dpy(2, vvl(2, vl(K+1, BIG)));
	rep(f, 0, 1) rep(k,0,K) dpy[1][f][k] = -BIG;
	dpy[0][0][0] = 0;
	dpy[1][0][0] = 0;


	vvvl dpx(2, vvl(2, vl(K+1, BIG)));
	rep(f, 0, 1) rep(k,0,K) dpx[1][f][k] = -BIG;
	dpx[0][0][0] = 0;
	dpx[1][0][0] = 0;

	{
		rep(i,1,N) {
			vvvl prey(2, vvl(2, vl(K+1, BIG)));
			rep(f, 0, 1) rep(k,0,K) prey[1][f][k] = -BIG;
			swap(prey, dpy);

			if(S[i] == 'L' || S[i] == 'R') {
				dpy = prey;
				continue;
			}
			
			rep(m, 0, 1) {
				rep(f, 0, 1) {
					rep(k, 0, K) if(abs(prey[m][f][k]) < big) {
						ll c = 1;
						if(S[i] == 'D') c = -1;
						if(f) c *= -1;//反転。

						//unuse
						if(m==0) chmin(dpy[m][f][k], prey[m][f][k] + c);
						else chmax(dpy[m][f][k], prey[m][f][k] + c);


						if(k != K) {//use
						    c *= -1;
							ll nf = f ^ 1;
							ll nk = k + 1;
							if(m==0) chmin(dpy[m][nf][nk], prey[m][f][k] + c);
							else chmax(dpy[m][nf][nk], prey[m][f][k] + c);

						}
					}
				}
			}
		}
	}


	{
		rep(i,1,N) {
			vvvl prex(2, vvl(2, vl(K+1, BIG)));
			rep(f, 0, 1) rep(k,0,K) prex[1][f][k] = -BIG;
			swap(prex, dpx);

			if(S[i] == 'D' || S[i] == 'U') {
				dpx = prex;
				continue;
			}
			
			rep(m, 0, 1) {
				rep(f, 0, 1) {
					rep(k, 0, K) if(abs(prex[m][f][k]) < big) {
						ll c = 1;
						if(S[i] == 'L') c = -1;
						if(f) c *= -1;//反転。

						//unuse
						if(m==0) chmin(dpx[m][f][k], prex[m][f][k] + c);
						else chmax(dpx[m][f][k], prex[m][f][k] + c);


						if(k != K) {//use
						    c *= -1;
							ll nf = f ^ 1;
							ll nk = k + 1;
							if(m==0) chmin(dpx[m][nf][nk], prex[m][f][k] + c);
							else chmax(dpx[m][nf][nk], prex[m][f][k] + c);

						}
					}
				}
			}
		}
	}




    ll ans = -BIG;
	rep(d, 0, K) {
		//上にd。
	
		ll ansx = -BIG;
		rep(m,0,1) rep(f, 0, 1) rep(k, 0, K-d) if(abs(dpx[m][f][k]) < big) chmax(ansx, abs(dpx[m][f][k]));

		ll ansy = -BIG;
		rep(m,0,1) rep(f, 0, 1) rep(k, 0, d) if(abs(dpy[m][f][k]) < big)  chmax(ansy, abs(dpy[m][f][k]));

		chmax(ans, ansx + ansy);

	}
    


	cout << ans << endl;
	
    

    
    

}



int main() {
    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    cout << fixed << setprecision(15);
    ll T = 1;
    //cin >> T;
    rep(i, 1, T) {
        solve();
    }
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 3596
final_rank: 4

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    string s; cin >> s;
    int n = s.size();
    vector<pair<int,int>> v(n);
    for (int i = 0; i < n; ++i) {
        if (s[i] == 'U') v[i] = {0, 1};
        else if (s[i] == 'L') v[i] = {-1, 0};
        else if (s[i] == 'D') v[i] = {0, -1};
        else v[i] = {1, 0};
    }
    int K; cin >> K;
    int res = 0;
    vector<vector<vector<int>>> dp(2, vector<vector<int>> (2, vector<int>(K+1, -1e9)));
    dp[0][0][0] = 0;
    dp[0][1][0] = 0;
    dp[1][0][0] = 0;
    dp[1][1][0] = 0;
    for (int i = 0; i < n; ++i) {
        vector<vector<vector<int>>> ndp(2, vector<vector<int>> (2, vector<int>(K+1, -1e9)));
        for (int j = 0; j < 2; ++j) {
            for (int k = 0; k < 2; ++k) {
                for (int l = 0; l <= K; ++l) {
                    if (dp[j][k][l] == -1e9) continue;
                    // そのまま
                    {
                        int nxt = dp[j][k][l] + v[i].first * (j == 0 ? 1 : -1) + v[i].second * (k == 0 ? 1 : -1);
                        ndp[j][k][l] = max(ndp[j][k][l], nxt);
                    }
                    // 魔法1
                    if (l+1 <= K) {
                        int nxt = dp[j][k][l] + v[i].first * (j == 1 ? 1 : -1) + v[i].second * (k == 0 ? 1 : -1);
                        ndp[j^1][k][l+1] = max(ndp[j^1][k][l+1], nxt);
                    }
                    // 魔法2
                    if (l+1 <= K) {
                        int nxt = dp[j][k][l] + v[i].first * (j == 0 ? 1 : -1) + v[i].second * (k == 1 ? 1 : -1);
                        ndp[j][k^1][l+1] = max(ndp[j][k^1][l+1], nxt);
                    }
                    // 両方
                    if (l+2 <= K) {
                        int nxt = dp[j][k][l] + v[i].first * (j == 1 ? 1 : -1) + v[i].second * (k == 1 ? 1 : -1);
                        ndp[j^1][k^1][l+2] = max(ndp[j^1][k^1][l+2], nxt);
                    }
                }
            }
        }
        swap(dp, ndp);
    }
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 2; ++j) {
            for (int k = 0; k <= K; ++k) {
                res = max(res, dp[i][j][k]);
            }
        }
    }
    cout << res << endl;
}
accuracy: 1
time_ms: 50
memory_kb: 3540
final_rank: 5

code_snippet: #include<bits/stdc++.h>
#pragma GCC optimize("Ofast")
//#pragma GCC target("avx2")
#pragma GCC optimize("unroll-loops")
using namespace std;
//#include<boost/multiprecision/cpp_int.hpp>
//#include<boost/multiprecision/cpp_dec_float.hpp>
//namespace mp=boost::multiprecision;
//#define mulint mp::cpp_int
//#define mulfloat mp::cpp_dec_float_100
struct __INIT{__INIT(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(15);}} __init;
#define INF (1<<30)
#define LINF (lint)(1LL<<56)
#define endl "\n"
#define rep(i,n) for(lint (i)=0;(i)<(n);(i)++)
#define reprev(i,n) for(lint (i)=(n-1);(i)>=0;(i)--)
#define flc(x) __builtin_popcountll(x)
#define pint pair<int,int>
#define pdouble pair<double,double>
#define plint pair<lint,lint>
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define vec vector<lint>
#define nep(x) next_permutation(all(x))
typedef long long lint;
int dx[8]={1,1,0,-1,-1,-1,0,1};
int dy[8]={0,1,1,1,0,-1,-1,-1};
const int MAX_N=4e5+5;
template<class T>bool chmax(T &a,const T &b){if(a<b){a=b;return 1;}return 0;}
template<class T>bool chmin(T &a,const T &b){if(b<a){a=b;return 1;}return 0;}
//vector<int> bucket[MAX_N/1000];
constexpr int MOD=1000000007;
//constexpr int MOD=998244353;
/*#include<atcoder/all>
using namespace atcoder;
typedef __int128_t llint;*/

int main(void){
    string S;
    cin >> S;
    int K;
    cin >> K;
    int N=S.length();
    int ans=0;
    rep(x,2) rep(y,2){
        int A[N]={},B[N]={};
        rep(i,N){
            if(S[i]=='L'){
                if(x==1) A[i]=1;
                else A[i]=-1;
            }
            if(S[i]=='R'){
                if(x==1) A[i]=-1;
                else A[i]=1;
            }
            if(S[i]=='U'){
                if(y==1) B[i]=1;
                else B[i]=-1;
            }
            if(S[i]=='D'){
                if(y==1) B[i]=-1;
                else B[i]=1;
            }
        }
        int dp1[N+1][K+1],dp2[N+1][K+1];
        rep(i,N+1) rep(j,K+1) dp1[i][j]=-INF,dp2[i][j]=-INF;
        dp1[0][0]=0,dp2[0][0]=0;
        rep(i,N) rep(j,K+1){
            if(dp1[i][j]==-INF) continue;
            int nxt=A[i];
            if(j%2) nxt*=-1;
            if(j!=K) chmax(dp1[i+1][j+1],dp1[i][j]+nxt*-1);
            chmax(dp1[i+1][j],dp1[i][j]+nxt);
        }
        rep(i,N) rep(j,K+1){
            if(dp2[i][j]==-INF) continue;
            int nxt=B[i];
            if(j%2) nxt*=-1;
            if(j!=K) chmax(dp2[i+1][j+1],dp2[i][j]+nxt*-1);
            chmax(dp2[i+1][j],dp2[i][j]+nxt);
        }
        int amax[K+1],bmax[K+1];
        rep(i,K+1) amax[i]=-INF,bmax[i]=-INF;
        amax[0]=dp1[N][0],bmax[0]=dp2[N][0];
        rep(i,K){
            amax[i+1]=max(dp1[N][i+1],amax[i]);
            bmax[i+1]=max(dp2[N][i+1],bmax[i]);
        }
        rep(i,K+1){
            chmax(ans,amax[i]+bmax[K-i]);
        }
    }
    cout << ans << endl;
}
accuracy: 1
time_ms: 30
memory_kb: 34680
final_rank: 9

code_snippet: #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
using PII = pair<ll, ll>;
#define FOR(i,a,n) for(ll i=(ll)a; i<(ll)n; ++i)
#define REP(i,n) FOR(i,0,n)
int dp[2001][2001][2][2];
int main() {
	string S;
	cin >> S;
	int K;
	cin >> K;
	int N = S.size();
	int ans = 0;
	for (int rx = 0; rx < 2; rx++) {
		for (int ry = 0; ry < 2; ry++) {
			fill((int*)dp, (int*)(dp + N + 1), -(1 << 30));
			dp[0][0][rx][ry] = 0;
			for (int i = 0; i < N; i++) {
				for (int j = 0; j <= K; j++) {
					for (int k = 0; k < 2; k++) {
						for (int l = 0; l < 2; l++) {
							if (dp[i][j][k][l] == -(1 << 30)) continue;
							int x = 0, y = 0;
							if (S[i] == 'R')  x = 1;
							else if (S[i] == 'L') x = -1;
							else if (S[i] == 'U') y = 1;
							else y = -1;
							if (k) x *= -1;
							if (l) y *= -1;
							//操作をしない
							dp[i + 1][j][k][l] = max(dp[i + 1][j][k][l], dp[i][j][k][l] + x + y);
							if (j == K) continue;
							//x反転
							dp[i + 1][j + 1][k ^ 1][l] = max(dp[i + 1][j + 1][k ^ 1][l], dp[i][j][k][l] - x + y);
							//y反転
							dp[i + 1][j + 1][k][l ^ 1] = max(dp[i + 1][j + 1][k][l ^ 1], dp[i][j][k][l] + x - y);
						}
					}
				}
			}
			for (int i = 0; i <= K; i++) {
				for (int j = 0; j < 2; j++) {
					for (int k = 0; k < 2; k++) {
						ans = max(ans, dp[N][i][j][k]);
					}
				}
			}
		}
	}
	cout << ans << endl;

}
accuracy: 1
time_ms: 190
memory_kb: 65776
final_rank: 17

code_snippet: #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
using PII = pair<ll, ll>;
#define FOR(i,a,n) for(ll i=(ll)a; i<(ll)n; ++i)
#define REP(i,n) FOR(i,0,n)
int dp[2001][2001][2][2];
int main() {
	string S;
	cin >> S;
	int K;
	cin >> K;
	int N = S.size();
	int ans = 0;
	for (int rx = 0; rx < 2; rx++) {
		for (int ry = 0; ry < 2; ry++) {
			memset(dp, -1, sizeof(dp));
			dp[0][0][rx][ry] = 0;
			for (int i = 0; i < N; i++) {
				for (int j = 0; j <= K; j++) {
					for (int k = 0; k < 2; k++) {
						for (int l = 0; l < 2; l++) {
							int x = 0, y = 0;
							if (S[i] == 'R')  x = 1;
							else if(S[i]=='L') x = -1;
							else if (S[i] == 'U') y = 1;
							else y = -1;
							if (k) x *= -1;
							if (l) y *= -1;
							//操作をしない
							dp[i + 1][j][k][l] = max(dp[i + 1][j][k][l], dp[i][j][k][l] + x + y);
							if (j == K) continue;
							//x反転
							dp[i + 1][j + 1][k ^ 1][l] = max(dp[i + 1][j + 1][k ^ 1][l], dp[i][j][k][l] - x + y);
							//y反転
							dp[i + 1][j + 1][k][l ^ 1] = max(dp[i + 1][j + 1][k][l ^ 1], dp[i][j][k][l] + x - y);
						}
					}
				}
			}
			for (int i = 0; i <= K; i++) {
				for (int j = 0; j < 2; j++) {
					for (int k = 0; k < 2; k++) {
						ans = max(ans, dp[N][i][j][k]);
					}
				}
			}
		}
	}
	cout << ans << endl;

}
accuracy: 0.59375
time_ms: 270
memory_kb: 65776
final_rank: 20

code_snippet: #define _USE_MATH_DEFINES

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>

using namespace std;

typedef pair<long long int, long long int> P;

long long int INF = 1e18;
long long int MOD = 1e9 + 7;

long long int DP[2100][2100];
long long int res[2100][2] = {};

int main(){
    string SS, S[2] = {"", ""}, hoge = " ";
    cin >> SS;
    int K;
    cin >> K;
    for(int i = 0; i < SS.size(); i++){
        if(SS[i] == 'L' || SS[i] == 'R'){
            hoge[0] = '0' + (SS[i] == 'R');
            S[0] += hoge;
        }else{
            hoge[0] = '0' + (SS[i] == 'U');
            S[1] += hoge;
        }
    }
    for(int n = 0; n < 2; n++){
        for(int p = 0; p < 2; p++){
            for(int i = 0; i < 2100; i++){
                for(int j = 0; j < 2100; j++){
                    DP[i][j] = -INF;
                }
            }
            DP[0][0] = 0;
            for(int i = 0; i < S[n].size(); i++){
                for(int j = 0; j <= K; j++){
                    if(S[n][i] == '0' + (p + j) % 2){
                        DP[i + 1][j] = max(DP[i + 1][j], DP[i][j] - 1);
                    }else{
                        DP[i + 1][j] = max(DP[i + 1][j], DP[i][j] + 1);
                    }
                    DP[i][j + 1] = max(DP[i][j + 1], DP[i][j]);
                }
            }
            for(int j = 0; j <= K; j++){
                DP[S[n].size()][j + 1] = max(DP[S[n].size()][j + 1], DP[S[n].size()][j]);
                res[j][n] = max(res[j][n], DP[S[n].size()][j]);
            }
        }
    }
    long long int ans = 0;
    for(int i = 0; i <= K; i++){
        ans = max(ans, res[i][0] + res[K - i][1]);
    }
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 37704
final_rank: 11

code_snippet: /*  -*- coding: utf-8 -*-
 *
 * 2809.cc: Graduation Ceremony
 */

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#include<complex>
#include<functional>
 
using namespace std;

/* constant */

const int MAX_N = 2000;
const int MAX_K = 2000;
const int MINF = 1 << 31;

const char cs[] = "RULD";
const int dxs[] = { 1, 0, -1, 0 }, dys[] = { 0, 1, 0, -1 };

const int qxs[] = { 1, -1, -1, 1 }, qys[] = { 1, 1, -1, -1 };
const int rxs[] = { 1, -1, 1, -1 }, rys[] = { 1, 1, -1, -1 };
const int bnums[] = { 0, 1, 1, 2 };


/* typedef */

/* global variables */

int cdis[256], dp[2][MAX_K + 1][4];
char s[MAX_N + 4];

/* subroutines */

inline void setmax(int &a, int b) { if (a < b) a = b; }

/* main */

int main() {
  for (int di = 0; di < 4; di++) cdis[cs[di]] = di;

  int k;
  scanf("%s%d", s, &k);

  int maxd = MINF;
  for (int q = 0; q < 4; q++) {
    const int &qx = qxs[q], &qy = qys[q];

    int cur = 0, nxt = 1;
    for (int j = 0; j <= k; j++)
      fill(dp[cur][j], dp[cur][j] + 4, MINF);
    fill(dp[cur][0], dp[cur][0] + 4, 0);

    for (int i = 0; s[i]; i++) {
      for (int j = 0; j <= k; j++)
	fill(dp[nxt][j], dp[nxt][j] + 4, MINF);

      int &di = cdis[s[i]];
      int dx = dxs[di] * qx, dy = dys[di] * qy;

      for (int j = 0; j <= k; j++)
	for (int r = 0; r < 4; r++)
	  if (dp[cur][j][r] > MINF)
	    for (int r1 = 0; r1 < 4; r1++) {
	      const int &b = bnums[r1];
	      if (j + b <= k) {
		const int r2 = r ^ r1;
		setmax(dp[nxt][j + b][r2],
		       dp[cur][j][r] + dx * rxs[r2] + dy * rys[r2]);
	      }
	    }
      cur ^= 1, nxt ^= 1;
    }

    for (int j = 0; j <= k; j++)
      for (int r = 0; r < 4; r++)
	setmax(maxd, dp[cur][j][r]);
  }

  printf("%d\n", maxd);
  return 0;
}
accuracy: 1
time_ms: 300
memory_kb: 3288
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;

int val[2][2000] = {};
int dp_max[2][2001][2001] = {};
int dp_min[2][2001][2001] = {};

int main() {
    string s;
    int K;
    cin >> s >> K;

    for (int i = 0; i < s.size(); i++) {
        char c = s[i];
        if (c == 'U') val[0][i] = 1;
        else if (c == 'D') val[0][i] = -1;
        else if (c == 'L') val[1][i] = 1;
        else val[1][i] = -1;
    }

    int len = s.size();
    for (int i = 0; i < len; i++) {
        int sign = 1;
        for (int k = 0; k <= K; k++, sign *= -1) {
            for (int type = 0; type < 2; type++) {
                int v = val[type][i] * sign;
                if (i > 0) {
                    dp_max[type][i][k] = dp_max[type][i-1][k];
                    dp_min[type][i][k] = dp_min[type][i-1][k];
                    if (k > 0) {
                        dp_max[type][i][k] = max(dp_max[type][i][k], dp_max[type][i-1][k-1]);
                        dp_min[type][i][k] = min(dp_min[type][i][k], dp_min[type][i-1][k-1]);
                    }
                }
                dp_max[type][i][k] += v;
                dp_min[type][i][k] += v;
            }
        }
    }

    if(false) {
    cout << "dp_max" << endl;
    for (int type = 0; type < 2; type++) {
        cout << (type == 0 ? "UD" : "RL") << endl;
        for (int i = 0; i < len; i++) {
            cout << val[type][i] << ": ";
            for (int k = 0; k <= K; k++) {
                cout << dp_max[type][i][k] << " ";
            }
            cout << endl;
        }
        cout << endl;
    }
    cout << "dp_min" << endl;
    for (int type = 0; type < 2; type++) {
        cout << (type == 0 ? "UD" : "RL") << endl;
        for (int i = 0; i < len; i++) {
            cout << val[type][i] << ": ";
            for (int k = 0; k <= K; k++) {
                cout << dp_max[type][i][k] << " ";
            }
            cout << endl;
        }
        cout << endl;
    }
    }

    int ans = 0;
    for (int k_limit = 0; k_limit <= K; k_limit++) {
        int lr = 0, ud = 0;
        for (int i = 0; i <= k_limit; i++) {
            ud = max(ud, abs(dp_max[0][len-1][i]));
            ud = max(ud, abs(dp_min[0][len-1][i]));
        }
        for (int i = 0; i <= K-k_limit; i++) {
            lr = max(lr, abs(dp_max[1][len-1][i]));
            lr = max(lr, abs(dp_min[1][len-1][i]));
        }
        ans = max(ans, lr + ud);
    }
    cout << ans << endl;
}
accuracy: 1
time_ms: 40
memory_kb: 65728
final_rank: 13

code_snippet: #include <bits/stdc++.h>

using namespace std;

const bool debug = true;
#define dbg(...) if(debug) printf(__VA_ARGS__)
#define print(var) if (debug) cout << #var << " = " << var << endl

namespace {
    /** output whole vector. ex) vector<int>{1, 2, 3} -> '1 2 3'. */
    template<typename T>
    ostream& operator<<(ostream& os, const vector<T>& xs) {
       if (xs.empty()) return os;
       os << xs[0];
       for (auto i = 1; i < xs.size(); i++) os << ' ' << xs[i];
       return os;
    }

    string S;
    int K;
    void input() {
        cin >> S >> K;
    }

    void normalize(vector<int>& xs) {
        if (xs.empty()) return;
        if (xs[0] == 1) {
            for (auto& x : xs) x = !x;
        }
    }

    void solve() {
        int N = S.size();
        vector<int> s[2];
        auto map_int = [&](char c) {
            return int(c == 'R' || c == 'U');
        };
        for (int i = 0; i < N; i++) {
            char c = S[i];
            s[int(c == 'R' || c == 'L')].push_back(map_int(c));
        }
        normalize(s[0]); normalize(s[1]);
        static int cache[2][2][2002][2002];
        const int INF = 1<<28;
        for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 2002; k++) for (int l = 0; l < 2002; l++) cache[i][j][k][l] = -INF;
        function<int(int, int, int, int)> f = [&](int w, int flip, int i, int k) {
            auto& t = s[w];
            auto& ans = cache[w][flip][i][k];
            if (k < 0) return -INF;
            if (i == t.size()) return 0;
            if (ans >= 0) return ans;
            return ans = max(f(w, !flip, i + 1, k - 1) + (t[i] == !flip ? +1 : -1),
                             f(w, flip, i + 1, k) + (t[i] == flip ? +1 : -1));
        };
        int ans = -INF;
        for (int k = 0; k <= K; k++) {
            for (int p = 0; p <= 1; p++) {
                for (int q = 0; q <= 1; q++) {
                    ans = max(ans, f(0, p, 0, k) + f(1, q, 0, K - k));
                }
            }
        }
        cout << ans << endl;
    }
}

int main() {
    input(); solve();
    return 0;
}
accuracy: 1
time_ms: 220
memory_kb: 65892
final_rank: 18

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


char buf[2001];
int yoko[2001],tate[2001];
int dp_yoko_plus[2000][2001],dp_yoko_minus[2000][2001];
int dp_tate_plus[2000][2001],dp_tate_minus[2000][2001];


int main(){

	int K;
	scanf("%s",buf);
	scanf("%d",&K);

	int yoko_index = 0,tate_index = 0;
	for(int i = 0; buf[i] != '\0'; i++){
		if(buf[i] == 'L' || buf[i] == 'R'){
			if(buf[i] == 'L'){
				yoko[yoko_index++] = -1;
			}else{
				yoko[yoko_index++] = 1;
			}
		}else{
			if(buf[i] == 'D'){
				tate[tate_index++] = -1;
			}else{
				tate[tate_index++] = 1;
			}
		}
	}

	for(int i = 0; i < yoko_index; i++){
		for(int a = 0; a <= K; a++){
			dp_yoko_plus[i][a] = -BIG_NUM;
			dp_yoko_minus[i][a] = BIG_NUM;
		}
	}

	dp_yoko_plus[0][0] = 0;
	dp_yoko_minus[0][0] = 0;

	for(int i = 0; i < yoko_index; i++){
		for(int used = 0; used <= min(i,K); used++){
			if(used%2 == 0){

				if(used < K){
					dp_yoko_plus[i+1][used+1] = max(dp_yoko_plus[i+1][used+1],dp_yoko_plus[i][used]+yoko[i]*(-1));
					dp_yoko_minus[i+1][used+1] = min(dp_yoko_minus[i+1][used+1],dp_yoko_minus[i][used]+yoko[i]*(-1));
				}

				dp_yoko_plus[i+1][used] = max(dp_yoko_plus[i+1][used],dp_yoko_plus[i][used]+yoko[i]);
				dp_yoko_minus[i+1][used] = min(dp_yoko_minus[i+1][used],dp_yoko_minus[i][used]+yoko[i]);

			}else{
				if(used < K){
					dp_yoko_plus[i+1][used+1] = max(dp_yoko_plus[i+1][used+1],dp_yoko_plus[i][used]+yoko[i]);
					dp_yoko_minus[i+1][used+1] = min(dp_yoko_minus[i+1][used+1],dp_yoko_minus[i][used]+yoko[i]);
				}

				dp_yoko_plus[i+1][used] = max(dp_yoko_plus[i+1][used],dp_yoko_plus[i][used]+yoko[i]*(-1));
				dp_yoko_minus[i+1][used] = min(dp_yoko_minus[i+1][used],dp_yoko_minus[i][used]+yoko[i]*(-1));
			}
		}
	}

	for(int i = 0; i < tate_index; i++){
		for(int a = 0; a <= K; a++){
			dp_tate_plus[i][a] = -BIG_NUM;
			dp_tate_minus[i][a] = BIG_NUM;
		}
	}

	dp_tate_plus[0][0] = 0;
	dp_tate_minus[0][0] = 0;

	for(int i = 0; i < tate_index; i++){
		for(int used = 0; used <= min(i,K); used++){
			if(used%2 == 0){

				if(used < K){
					dp_tate_plus[i+1][used+1] = max(dp_tate_plus[i+1][used+1],dp_tate_plus[i][used]+tate[i]*(-1));
					dp_tate_minus[i+1][used+1] = min(dp_tate_minus[i+1][used+1],dp_tate_minus[i][used]+tate[i]*(-1));
				}

				dp_tate_plus[i+1][used] = max(dp_tate_plus[i+1][used],dp_tate_plus[i][used]+tate[i]);
				dp_tate_minus[i+1][used] = min(dp_tate_minus[i+1][used],dp_tate_minus[i][used]+tate[i]);

			}else{

				if(used < K){
					dp_tate_plus[i+1][used+1] = max(dp_tate_plus[i+1][used+1],dp_tate_plus[i][used]+tate[i]);
					dp_tate_minus[i+1][used+1] = min(dp_tate_minus[i+1][used+1],dp_tate_minus[i][used]+tate[i]);
				}

				dp_tate_plus[i+1][used] = max(dp_tate_plus[i+1][used],dp_tate_plus[i][used]+tate[i]*(-1));
				dp_tate_minus[i+1][used] = min(dp_tate_minus[i+1][used],dp_tate_minus[i][used]+tate[i]*(-1));
			}
		}
	}

	int ans = 0;

	for(int a = 0; a <= K; a++){
		for(int b = 0; b <= K-a; b++){

			ans = max(ans,max(dp_yoko_plus[yoko_index][a],abs(dp_yoko_minus[yoko_index][a]))
					+max(dp_tate_plus[tate_index][b],abs(dp_tate_minus[tate_index][b])));
		}
	}

	printf("%d\n",ans);

	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 34508
final_rank: 8

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


char buf[2001];
int yoko[2001],tate[2001];
int dp_yoko_plus[2000][2001],dp_yoko_minus[2000][2001];
int dp_tate_plus[2000][2001],dp_tate_minus[2000][2001];


int main(){

	int K;
	scanf("%s",buf);
	scanf("%d",&K);

	int yoko_index = 0,tate_index = 0;
	for(int i = 0; buf[i] != '\0'; i++){
		if(buf[i] == 'L' || buf[i] == 'R'){
			if(buf[i] == 'L'){
				yoko[yoko_index++] = -1;
			}else{
				yoko[yoko_index++] = 1;
			}
		}else{
			if(buf[i] == 'D'){
				tate[tate_index++] = -1;
			}else{
				tate[tate_index++] = 1;
			}
		}
	}

	for(int i = 0; i < yoko_index; i++){
		for(int a = 0; a <= K; a++){
			dp_yoko_plus[i][a] = -BIG_NUM;
			dp_yoko_minus[i][a] = BIG_NUM;
		}
	}

	dp_yoko_plus[0][0] = 0;
	dp_yoko_minus[0][0] = 0;

	for(int i = 0; i < yoko_index; i++){
		for(int used = 0; used <= min(i,K); used++){
			if(used%2 == 0){

				if(used < K){
					dp_yoko_plus[i+1][used+1] = max(dp_yoko_plus[i+1][used+1],dp_yoko_plus[i][used]+yoko[i]*(-1));
					dp_yoko_minus[i+1][used+1] = min(dp_yoko_minus[i+1][used+1],dp_yoko_minus[i][used]+yoko[i]*(-1));
				}

				dp_yoko_plus[i+1][used] = max(dp_yoko_plus[i+1][used],dp_yoko_plus[i][used]+yoko[i]);
				dp_yoko_minus[i+1][used] = min(dp_yoko_minus[i+1][used],dp_yoko_minus[i][used]+yoko[i]);

			}else{
				if(used < K){
					dp_yoko_plus[i+1][used+1] = max(dp_yoko_plus[i+1][used+1],dp_yoko_plus[i][used]+yoko[i]);
					dp_yoko_minus[i+1][used+1] = min(dp_yoko_minus[i+1][used+1],dp_yoko_minus[i][used]+yoko[i]);
				}

				dp_yoko_plus[i+1][used] = max(dp_yoko_plus[i+1][used],dp_yoko_plus[i][used]+yoko[i]*(-1));
				dp_yoko_minus[i+1][used] = min(dp_yoko_minus[i+1][used],dp_yoko_minus[i][used]+yoko[i]*(-1));
			}
		}
	}

	for(int i = 0; i < tate_index; i++){
		for(int a = 0; a <= K; a++){
			dp_tate_plus[i][a] = -BIG_NUM;
			dp_tate_minus[i][a] = BIG_NUM;
		}
	}

	dp_tate_plus[0][0] = 0;
	dp_tate_minus[0][0] = 0;

	for(int i = 0; i < tate_index; i++){
		for(int used = 0; used <= min(i,K); used++){
			if(used%2 == 0){

				if(used < K){
					dp_tate_plus[i+1][used+1] = max(dp_tate_plus[i+1][used+1],dp_tate_plus[i][used]+tate[i]*(-1));
					dp_tate_minus[i+1][used+1] = min(dp_tate_minus[i+1][used+1],dp_tate_minus[i][used]+tate[i]*(-1));
				}

				dp_tate_plus[i+1][used] = max(dp_tate_plus[i+1][used],dp_tate_plus[i][used]+tate[i]);
				dp_tate_minus[i+1][used] = min(dp_tate_minus[i+1][used],dp_tate_minus[i][used]+tate[i]);

			}else{

				if(used < K){
					dp_tate_plus[i+1][used+1] = max(dp_tate_plus[i+1][used+1],dp_tate_plus[i][used]+tate[i]);
					dp_tate_minus[i+1][used+1] = min(dp_tate_minus[i+1][used+1],dp_tate_minus[i][used]+tate[i]);
				}

				dp_tate_plus[i+1][used] = max(dp_tate_plus[i+1][used],dp_tate_plus[i][used]+tate[i]*(-1));
				dp_tate_minus[i+1][used] = min(dp_tate_minus[i+1][used],dp_tate_minus[i][used]+tate[i]*(-1));
			}
		}
	}

	int ans = 0;

	for(int a = 0; a <= K; a++){
		for(int b = 0; b <= K; b++){
			if(a+b > K)break;

			ans = max(ans,max(dp_yoko_plus[yoko_index][a],abs(dp_yoko_minus[yoko_index][a]))
					+max(dp_tate_plus[tate_index][b],abs(dp_tate_minus[tate_index][b])));
		}
	}

	printf("%d\n",ans);

	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 34492
final_rank: 7

code_snippet: #include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <string>
#include <algorithm>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <functional>
#include <iostream>
#define MOD 1000000007LL
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
 
//[?????????¨????????????£??????][???????????????¨??????°][??????????????????£???????????????]
int dp[2][2001][2];
int dp2[2][2001][2];
int tmp[2001][2];
int tmp2[2001][2];
string str;
int sumx[2001];
int sumy[2001];
int n,k;
 
int main(void){
    cin >> str;
    n=str.size();
    scanf("%d",&k);
    for(int i=0;i<=k;i++){
        for(int j=0;j<2;j++){
            dp[0][i][j]=-3000;
            dp2[0][i][j]=3000;
            dp[1][i][j]=-3000;
            dp2[1][i][j]=3000;
        }
    }
    dp[0][0][0]=0;
    dp[1][0][0]=0;
    dp2[0][0][0]=0;
    dp2[1][0][0]=0;
 
    for(int aa=0;aa<n;aa++){
        for(int i=0;i<=k;i++){
            for(int j=0;j<2;j++){
                tmp[i][j]=-3000;
                tmp2[i][j]=3000;
            }
        }
        for(int i=0;i<=k;i++){
            if(str[aa]=='U' || str[aa]=='D'){
                for(int j=0;j<2;j++){
                    tmp[i][j]=max(tmp[i][j],dp[0][i][j]);
                    tmp2[i][j]=min(tmp2[i][j],dp2[0][i][j]);
                }
            }
            if(str[aa]=='L'){
                tmp[i][0]=max(tmp[i][0],dp[0][i][0]-1);
                tmp[i][1]=max(tmp[i][1],dp[0][i][1]+1);
                tmp2[i][0]=min(tmp2[i][0],dp2[0][i][0]-1);
                tmp2[i][1]=min(tmp2[i][1],dp2[0][i][1]+1);
                if(i+1<=k){
                    tmp[i+1][1]=max(tmp[i+1][1],dp[0][i][0]+1);
                    tmp[i+1][0]=max(tmp[i+1][0],dp[0][i][1]-1);
                    tmp2[i+1][1]=min(tmp2[i+1][1],dp2[0][i][0]+1);
                    tmp2[i+1][0]=min(tmp2[i+1][0],dp2[0][i][1]-1);
                }
            }
            if(str[aa]=='R'){
                tmp[i][0]=max(tmp[i][0],dp[0][i][0]+1);
                tmp[i][1]=max(tmp[i][1],dp[0][i][1]-1);
                tmp2[i][0]=min(tmp2[i][0],dp2[0][i][0]+1);
                tmp2[i][1]=min(tmp2[i][1],dp2[0][i][1]-1);
                if(i+1<=k){
                    tmp[i+1][1]=max(tmp[i+1][1],dp[0][i][0]-1);
                    tmp[i+1][0]=max(tmp[i+1][0],dp[0][i][1]+1);
                    tmp2[i+1][1]=min(tmp2[i+1][1],dp2[0][i][0]-1);
                    tmp2[i+1][0]=min(tmp2[i+1][0],dp2[0][i][1]+1);
                }
            }
        }
        for(int i=0;i<=k;i++){
            for(int j=0;j<2;j++){
                dp[0][i][j]=tmp[i][j];
                dp2[0][i][j]=tmp2[i][j];
            }
        }
    }
 
    for(int aa=0;aa<n;aa++){
        for(int i=0;i<=k;i++){
            for(int j=0;j<2;j++){
                tmp[i][j]=-3000;
                tmp2[i][j]=3000;
            }
        }
        for(int i=0;i<=k;i++){
            if(str[aa]=='L' || str[aa]=='R'){
                for(int j=0;j<2;j++){
                    tmp[i][j]=max(tmp[i][j],dp[1][i][j]);
                    tmp2[i][j]=min(tmp2[i][j],dp2[1][i][j]);
                }
            }
            if(str[aa]=='D'){
                tmp[i][0]=max(tmp[i][0],dp[1][i][0]-1);
                tmp[i][1]=max(tmp[i][1],dp[1][i][1]+1);
                tmp2[i][0]=min(tmp2[i][0],dp2[1][i][0]-1);
                tmp2[i][1]=min(tmp2[i][1],dp2[1][i][1]+1);
                if(i+1<=k){
                    tmp[i+1][1]=max(tmp[i+1][1],dp[1][i][0]+1);
                    tmp[i+1][0]=max(tmp[i+1][0],dp[1][i][1]-1);
                    tmp2[i+1][1]=min(tmp2[i+1][1],dp2[1][i][0]+1);
                    tmp2[i+1][0]=min(tmp2[i+1][0],dp2[1][i][1]-1);
                }
            }
            if(str[aa]=='U'){
                tmp[i][0]=max(tmp[i][0],dp[1][i][0]+1);
                tmp[i][1]=max(tmp[i][1],dp[1][i][1]-1);
                tmp2[i][0]=min(tmp2[i][0],dp2[1][i][0]+1);
                tmp2[i][1]=min(tmp2[i][1],dp2[1][i][1]-1);
                if(i+1<=k){
                    tmp[i+1][1]=max(tmp[i+1][1],dp[1][i][0]-1);
                    tmp[i+1][0]=max(tmp[i+1][0],dp[1][i][1]+1);
                    tmp2[i+1][1]=min(tmp2[i+1][1],dp2[1][i][0]-1);
                    tmp2[i+1][0]=min(tmp2[i+1][0],dp2[1][i][1]+1);
                }
            }
        }
        for(int i=0;i<=k;i++){
            for(int j=0;j<2;j++){
                dp[1][i][j]=tmp[i][j];
                dp2[1][i][j]=tmp2[i][j];
            }
        }
    }
 
    for(int i=0;i<2;i++){
        for(int j=1;j<=k;j++){
            for(int l=0;l<2;l++){
                dp[i][j][l]=max(dp[i][j][l],dp[i][j-1][l]);
                dp2[i][j][l]=min(dp2[i][j][l],dp2[i][j-1][l]);
            }
        }
    }
    int res=0;
    for(int i=0;i<=k;i++){
        int lr=max(max(dp[0][i][0],dp[0][i][1]),max(-dp2[0][i][0],-dp2[0][i][1]));
        int ud=max(max(dp[1][k-i][0],dp[1][k-i][1]),max(-dp2[1][k-i][0],-dp2[1][k-i][1]));
        res=max(res,lr+ud);
    }
    printf("%d\n",res);
    return 0;
}
accuracy: 1
time_ms: 70
memory_kb: 3408
final_rank: 6

code_snippet: #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <complex>
#include <cstring>

using namespace std;

#define rep(i,n) for(int i=0; i<(int)(n); i++)
#define X real()
#define Y imag()

// #define DEBUG

template<typename A,typename B>inline void chmin(A &a,B b){if(a>b)a=b;}
template<typename A,typename B>inline void chmax(A &a,B b){if(a<b)a=b;}

typedef complex<int> Pos;

int dp[2][2][2001][2001];

int N, K;
string S;

const int INF = 1e9;

/*
void dfs(int n, int k, int pos, bool dir_x, bool plus)
{
    cerr << n << " " << k << " " <<  pos << endl;

    if (~dp[dir_x][plus][n][k]) return dp[dir_x][plus][n][k];
    if (n == N) return dp[dir_x][plus][n][k] = pos;

    int diff;
    if (dir_x) {
        if (S[n] == 'L' || S[n] == 'R') {
            diff = (S[n] == 'R' ? 1 : -1);
        } else {
            diff = 0;
        }
    } else {
        if (S[n] == 'D' || S[n] == 'U') {
            diff = (S[n] == 'U' ? 1 : -1);
        } else {
            diff = 0;
        }
    }

    int mirror = (k%2 == 0 ? 1 : -1);
    int res = dfs(n+1, k, pos + (mirror * diff), dir_x, plus);
    if (k < K) {
        if (plus) res = max(res, dfs(n+1, k+1, pos + (mirror * diff * -1), dir_x, plus));
        else      res = min(res, dfs(n+1, k+1, pos + (mirror * diff * -1), dir_x, plus));
    }

    return dp[dir_x][plus][n][k] = res;
}
*/

int get_diff(char dir, bool dir_x)
{
    int diff;
    if (dir_x) {
        if (dir == 'L' || dir == 'R') {
            diff = (dir == 'R' ? 1 : -1);
        } else {
            diff = 0;
        }
    } else {
        if (dir == 'D' || dir == 'U') {
            diff = (dir == 'U' ? 1 : -1);
        } else {
            diff = 0;
        }
    }
    return diff;
}


int main()
{
    cin >> S >> K;    
    N = S.size();

    rep(dir_x, 2) rep(n, N+1) rep(k, K+1) dp[dir_x][0][n][k] = INF;
    rep(dir_x, 2) rep(n, N+1) rep(k, K+1) dp[dir_x][1][n][k] = -INF;
    rep(dir_x, 2) rep(plus, 2) rep(k, K+1) dp[dir_x][plus][0][k] = 0;
    

    rep(dir_x, 2) rep(plus, 2) {
        rep(n, N) rep(k, K+1) {
            int diff = get_diff(S[n], dir_x);
            int mirror = (k%2 == 0 ? 1 : -1);
            {
                int npos = dp[dir_x][plus][n][k] + mirror * diff;

                if (plus) chmax(dp[dir_x][plus][n+1][k], npos);
                else      chmin(dp[dir_x][plus][n+1][k], npos);
            }
            if (k < K) {
                int npos = dp[dir_x][plus][n][k] + mirror * diff * -1;
                if (plus) chmax(dp[dir_x][plus][n+1][k+1], npos);
                else      chmin(dp[dir_x][plus][n+1][k+1], npos);
            }
        }
    }

    int dp_abs[2][2001] = {};
    rep(k, K+1) {
        rep(dir_x, 2) {
            int mx = max(abs(dp[dir_x][0][N][k]), abs(dp[dir_x][1][N][k]));
            dp_abs[dir_x][k] = max(dp_abs[dir_x][k], mx);
        }
    }

    int ans = 0;
    rep(kx, K+1) {
        rep(ky, K+1) {
            if (kx + ky <= K) {
                ans = max(ans, dp_abs[0][ky] + dp_abs[1][kx]);
            }
        }
    }

    cout << ans << endl;
}
accuracy: 1
time_ms: 70
memory_kb: 65736
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;

using VI = vector<int>;
using VVI = vector<VI>;
using PII = pair<int, int>;
using LL = long long;
using VL = vector<LL>;
using VVL = vector<VL>;
using PLL = pair<LL, LL>;
using VS = vector<string>;

#define ALL(a)  begin((a)),end((a))
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SORT(c) sort(ALL((c)))
#define RSORT(c) sort(RALL((c)))

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

#define FF first
#define SS second
template<class S, class T>
istream& operator>>(istream& is, pair<S,T>& p){
  return is >> p.FF >> p.SS;
}
template<class S, class T>
ostream& operator<<(ostream& os, const pair<S,T>& p){
  return os << p.FF << " " << p.SS;
}
template<class T>
void maxi(T& x, T y){
  if(x < y) x = y;
}
template<class T>
void mini(T& x, T y){
  if(x > y) x = y;
}


const double EPS = 1e-10;
const double PI  = acos(-1.0);
const LL MOD = 1e9+7;

int dp_mn_x[2001][2001][2];
int dp_mx_x[2001][2001][2];
int dp_mn_y[2001][2001][2];
int dp_mx_y[2001][2001][2];

int main(){
  cin.tie(0);
  ios_base::sync_with_stdio(false);

  string S; cin >> S;
  int K; cin >> K;
  int N = SZ(S);

  fill((int*)dp_mn_x, (int*)dp_mn_x+2001*2001*2, 1e9);
  fill((int*)dp_mx_x, (int*)dp_mx_x+2001*2001*2, -1e9);
  fill((int*)dp_mn_y, (int*)dp_mn_y+2001*2001*2, 1e9);
  fill((int*)dp_mx_y, (int*)dp_mx_y+2001*2001*2, -1e9);
  dp_mn_x[0][0][0] = dp_mx_x[0][0][0] = dp_mn_y[0][0][0] = dp_mx_y[0][0][0] = 0;

  REP(i,N){
	REP(k,K+1){
	  REP(f,2){
		if(S[i] == 'L' || S[i] == 'R'){
		  mini(dp_mn_y[i+1][k][f], dp_mn_y[i][k][f]);
		  maxi(dp_mx_y[i+1][k][f], dp_mx_y[i][k][f]);

		  int dx = (S[i]=='L'?-1:1) * (f==0?1:-1);
		  mini(dp_mn_x[i+1][k][f], dp_mn_x[i][k][f] + dx);
		  mini(dp_mn_x[i+1][k+1][f^1], dp_mn_x[i][k][f] + dx * -1);
		  maxi(dp_mx_x[i+1][k][f], dp_mx_x[i][k][f] + dx);
		  maxi(dp_mx_x[i+1][k+1][f^1], dp_mx_x[i][k][f] + dx * -1);
		}
		else{
		  mini(dp_mn_x[i+1][k][f], dp_mn_x[i][k][f]);
		  maxi(dp_mx_x[i+1][k][f], dp_mx_x[i][k][f]);

		  int dx = (S[i]=='D'?-1:1) * (f==0?1:-1);
		  mini(dp_mn_y[i+1][k][f], dp_mn_y[i][k][f] + dx);
		  mini(dp_mn_y[i+1][k+1][f^1], dp_mn_y[i][k][f] + dx * -1);
		  maxi(dp_mx_y[i+1][k][f], dp_mx_y[i][k][f] + dx);
		  maxi(dp_mx_y[i+1][k+1][f^1], dp_mx_y[i][k][f] + dx * -1);
		}
	  }
	}
  }

  int ans = -1e9;
  REP(k1,K+1) REP(k2,K+1){
	if(k1+k2 > K) continue;
	REP(f1,2) REP(f2,2)
	  maxi(ans, max(-dp_mn_x[N][k1][f1], dp_mx_x[N][k1][f1])
		   + max(-dp_mn_y[N][k2][f2], dp_mx_y[N][k2][f2]));
  }
  cout << ans << endl;

  return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 128332
final_rank: 19

code_snippet: #include "bits/stdc++.h"
using namespace std;

void update(int &a, int b) {
	if (a < b)a = b;
}

int main() {
	string st; cin >> st;
	int K; cin >> K;
	vector<vector<int>>dp_l(st.size() + 1, vector<int>(K + 1, -10000));
	vector<vector<int>>dp_r(st.size() + 1, vector<int>(K + 1, -10000));
	vector<vector<int>>dp_u(st.size() + 1, vector<int>(K + 1, -10000));
	vector<vector<int>>dp_d(st.size() + 1, vector<int>(K + 1, -10000));
	dp_l[0][0] = 0;
	dp_r[0][0] = 0;
	dp_u[0][0] = 0;
	dp_d[0][0] = 0;
	for (int i = 0; i < st.size(); ++i) {
		char c = st[i];
		for (int magic_use = 0; magic_use <= K; ++magic_use) {
			bool rev = magic_use % 2;
			if ((c == 'L'&&!rev) || (c == 'R'&&rev)) {
				if (magic_use != K) {
					update(dp_r[i + 1][magic_use + 1], dp_r[i][magic_use] + 1);
				}
				update(dp_r[i + 1][magic_use], dp_r[i][magic_use] - 1);
				update(dp_l[i + 1][magic_use], dp_l[i][magic_use] + 1);
				update(dp_u[i + 1][magic_use], dp_u[i][magic_use]);
				update(dp_d[i + 1][magic_use], dp_d[i][magic_use]);
			}
			else if ((c == 'R'&&!rev) || (c == 'L'&&rev)) {
				if (magic_use != K) {
					update(dp_l[i + 1][magic_use + 1], dp_l[i][magic_use] + 1);
				}
				update(dp_r[i + 1][magic_use], dp_r[i][magic_use] + 1);
				update(dp_l[i + 1][magic_use], dp_l[i][magic_use] - 1);
				update(dp_u[i + 1][magic_use], dp_u[i][magic_use]);
				update(dp_d[i + 1][magic_use], dp_d[i][magic_use]);
			}
			else if ((c == 'U'&&!rev) || (c == 'D'&&rev)) {
				if (magic_use != K) {
					update(dp_d[i + 1][magic_use + 1], dp_d[i][magic_use] + 1);
				}
				update(dp_r[i + 1][magic_use], dp_r[i][magic_use]);
				update(dp_l[i + 1][magic_use], dp_l[i][magic_use]);
				update(dp_u[i + 1][magic_use], dp_u[i][magic_use] + 1);
				update(dp_d[i + 1][magic_use], dp_d[i][magic_use] - 1);
			}
			else {
				if (magic_use != K) {
					update(dp_u[i + 1][magic_use + 1], dp_u[i][magic_use] + 1);
				}
				update(dp_r[i + 1][magic_use], dp_r[i][magic_use]);
				update(dp_l[i + 1][magic_use], dp_l[i][magic_use]);
				update(dp_u[i + 1][magic_use], dp_u[i][magic_use] - 1);
				update(dp_d[i + 1][magic_use], dp_d[i][magic_use]+ 1);
			}
		}
	}
	int ans = 0;
	for (int y = 0; y <= K; ++y) {
		for (int x = 0; x <= K; ++x) {
			if (x + y <= K) {
				for (int i = 0; i < 4; ++i) {
					int sum = 0;
					if (i % 2)sum += dp_l[st.size()][x];
					else sum += dp_r[st.size()][x];

					if (i / 2)sum += dp_u[st.size()][y];
					else sum += dp_d[st.size()][y];

					update(ans, sum);
				}
			}
		}
	}
	cout << ans << endl;
	return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 65740
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,n) repl(i,0,n)
#define mp(a,b) make_pair((a),(b))
#define pb(a) push_back((a))
#define all(x) (x).begin(),(x).end()
#define uniq(x) sort(all(x)),(x).erase(unique(all(x)),end(x))
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}

#define INF 147483600

int k;

void solve(vector<char> &s, vector<int> &ans, string str){
  int n = s.size();
  if(n==0) return;
  for(auto c : str){
    vector<vector<int>> dp(n, vector<int>(k+1,-INF));
    dp[0][0] = (s[0]==c);
    dp[0][1] = (s[0]!=c);
    repl(i,1,n){
      dp[i][0] = dp[i-1][0] + (s[i]==c);
      repl(j,1,k+1){
        if(j%2==0) dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]) + (s[i]==c);
        else dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]) + (s[i]!=c);
      }
    }
    rep(i,k+1) ans[i] = max(ans[i], 2*dp[n-1][i]-n);
  }
}

int main(){
  string s;
  cin>>s>>k;

  vector<char> x,y;
  for(auto c: s){
    if(c=='R' || c=='L') x.pb(c);
    else y.pb(c);
  }

  vector<int> xx(k+1,0),yy(k+1,0);

  solve(x, xx, "RL");
  solve(y, yy, "UD");

  int ans = 0;
  rep(i,k+1) rep(j,k+1) if(i+j<=k) ans = max(ans, xx[i]+yy[j]);

  cout << ans << endl;

  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 10944
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;

typedef long long ll;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second

// 0:R????????°????????§???, 1:L????????°????????§???
int dp[2001][2001][2];
const string LR="LR";

void calc(string s, int K)
{
    int S=s.size();
    memset(dp,0,sizeof(dp));
    rep(i,S)rep(j,K+1)rep(k,2)
    {
        // ??????????????????
        dp[i+1][j][k] = max(dp[i+1][j][k], dp[i][j][k]+(s[i]==LR[(j%2+k+1)%2]));
        // ????????????
        if(j<K) dp[i+1][j+1][k] = max(dp[i+1][j+1][k], dp[i][j][k]+(s[i]==LR[(j%2+k)%2]));
    }
}

int main()
{
    cin.tie(0);ios::sync_with_stdio(false);

    string s;
    int K;
    cin >>s >>K;

    string x="",y="";
    rep(i,s.size())
    {
        if(s[i]=='L' || s[i]=='R') x+=s[i];
        else y+=(s[i]=='U')?'L':'R';
    }

    int X=x.size(), Y=y.size();
    // 0:R????????°????????§???, 1:L????????°????????§???
    int dx[2001]={};
    // 0:D????????°????????§???, 1:U????????°????????§???
    int dy[2001]={};

    calc(x,K);
    rep(i,K+1) dx[i]=max(2*dp[X][i][0]-X, 2*dp[X][i][1]-X);
    calc(y,K);
    rep(i,K+1) dy[i]=max(2*dp[Y][i][0]-Y, 2*dp[Y][i][1]-Y);

    int ans=0;
    rep(i,K+1)rep(j,K+1)if(i+j<=K) ans=max(ans,dx[i]+dy[j]);

    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 34468
final_rank: 10