//#pragma GCC optimize("O3")
//#pragma GCC target("arch=corei7-avx")
#include <bits/stdc++.h>
#ifndef ONLINE_JUDGE
# include <sys/time.h>
# include <sys/resource.h>
#endif

/*** TEMPLATE CODE STARTS HERE ***/

#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795028841971693993751
#endif

using namespace std;

typedef vector<string> vs;
typedef long long ll;
typedef complex<double> pnt;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

#define RA(x) begin(x), end(x)
#define FE(i, x) for (auto i = begin(x); i != end(x); ++i)
#define SZ(x) ((ll) (x).size())

template<class T>
void splitstr(const string &s, vector<T> &out)
{
    istringstream in(s);
    out.clear();
    copy(istream_iterator<T>(in), istream_iterator<T>(), back_inserter(out));
}

template<class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }

static void redirect(int argc, const char **argv)
{
#ifndef ONLINE_JUDGE
    struct rlimit rlim;
    getrlimit(RLIMIT_STACK, &rlim);
    rlim.rlim_cur = 256 * 1024 * 1024;
    setrlimit(RLIMIT_STACK, &rlim);
#ifndef __SANITIZE_ADDRESS__
    getrlimit(RLIMIT_DATA, &rlim);
    rlim.rlim_cur = 256 * 1024 * 1024;
    setrlimit(RLIMIT_DATA, &rlim);
#endif
#endif

    ios::sync_with_stdio(false);
    cin.tie(NULL);
    if (argc > 1)
    {
        static filebuf f;
        f.open(argv[1], ios::in);
        cin.rdbuf(&f);
        if (!cin)
        {
            cerr << "Failed to open '" << argv[1] << "'" << endl;
            exit(1);
        }
    }

    if (argc > 2)
    {
        static filebuf f;
        f.open(argv[2], ios::out | ios::trunc);
        cout.rdbuf(&f);
        if (!cout)
        {
            cerr << "Failed to open '" << argv[2] << "'" << endl;
        }
    }
    cin.exceptions(ios::failbit);
}

/*** TEMPLATE CODE ENDS HERE */

static ll choose[501][501];

int main(int argc, const char **argv)
{
    redirect(argc, argv);
    int N, M, P;
    cin >> N >> M >> P;
    for (int i = 0; i <= N; i++)
    {
        choose[i][0] = choose[i][i] = 1;
        for (int j = 1; j < i; j++)
            choose[i][j] = (choose[i - 1][j - 1] + choose[i - 1][j]) % P;
    }

    vector<ll> dp1(N + 1);
    vector<ll> dpw(N + 1);
    dp1[0] = 0;
    dpw[0] = 1;
    for (int m = 1; m <= M; m++)
    {
        for (int i = 0; i < m; i++)
        {
            ll w = dpw[i] * dpw[m - 1 - i] % P;
            w = w * choose[m - 1][i] % P;
            dpw[m] = (dpw[m] + w * (m + 1) % P) % P;

            ll s1 = dp1[i] * dpw[m - 1 - i] % P;
            ll s2 = dp1[m - 1 - i] * dpw[i] % P;
            ll add = (s1 + s2) % P * (m + 1) % P * choose[m - 1][i] % P;
            add += w * ((i * (i + 1) + (m - 1 - i) * (m - i)) / 2) % P;
            dp1[m] = (dp1[m] + add) % P;
        }
    }

    vector<vll> dp(N + 1, vll(N + 1)), dps(N + 1, vll(N + 1));
    dps[0][0] = 1;
    for (int i = 1; i <= N; i++)
    {
        dp[i][i] = dp1[i];
        dps[i][i] = dpw[i];
        dps[i][0] = 1;
        for (int j = 1; j < i; j++)
        {
            dp[i][j] = dp[i - 1][j];
            dps[i][j] = dps[i - 1][j];
            for (int k = 1; k <= j; k++)
            {
                dps[i][j] = (dps[i][j] + dpw[k] * dps[i - k - 1][j - k] % P * choose[j][k]) % P;
                ll add = (dp[i - k - 1][j - k] * dpw[k] % P + dps[i - k - 1][j - k] * dp1[k]) % P;
                dp[i][j] = (dp[i][j] + add * choose[j][k] % P) % P;
            }
        }
    }
    cout << dp[N][M] << '\n';

    return 0;
}


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

const int maxn = 510;

int m, n, mod;

inline int add (int x, int y) {return (1LL * x + y) % mod;}
inline int sub (int x, int y) {return x - y < 0 ? x - y + mod : x - y;}
inline int mul (int x, int y) {return 1LL * x * y % mod;}
int fac[maxn], inv[maxn], invfac[maxn];
void get_fac_and_inv(int n)
{
    fac[0] = inv[1] = fac[1] = invfac[0] = invfac[1] = 1LL;
    for (int i = 2; i <= n; i++) inv[i] = mul((mod - mod / i), inv[mod % i]);
    for (int i = 2; i <= n; i++) {fac[i] = mul (fac[i - 1], i); invfac[i] = mul (invfac[i - 1], inv[i]);}
}
inline int C (int n, int m) {if (n < m || m < 0) return 0; return mul(mul(fac[n], invfac[m]), invfac[n - m]);}
inline int P (int n, int m) {return C(n + m - 1, m - 1);}

int f[maxn], g[maxn], s[maxn];
int ff[maxn][maxn], gg[maxn][maxn];

int main()
{
    scanf ("%d %d %d", &n, &m, &mod);
    get_fac_and_inv (500);
    for (int i = 1; i <= n; i++) s[i] = add (s[i - 1], i);
    f[0] = 1; f[1] = 2;
    g[0] = 0; g[1] = 0;
    for (int i = 2; i <= n; i++)
    {
        for (int j = 0; j < i; j++)
        {
            int temp = mul (C (i - 1, j), mul(f[j], f[i - 1 - j]));
            f[i] = add (f[i], mul (temp, i + 1));
            g[i] = add (g[i], mul (temp, s[j] + s[i - 1 - j]));
            temp = mul (add (mul (g[j], f[i - 1 - j]), mul (g[i - 1 - j], f[j])), i + 1);
            g[i] = add (g[i], mul (temp, C(i - 1, j)));
        }
    }
    ff[0][0] = 1; gg[0][0] = 0;
    for (int i = 0; i <= m; i++)
        for (int j = 0; j <= m; j++)
        {
            if (!ff[i][j]) continue;
            for (int k = 1; k + j <= m; k++)
            {
                ff[i + 1][j + k] = add (ff[i + 1][j + k], mul (mul (ff[i][j], f[k]), C(j + k, k)));
                gg[i + 1][j + k] = add (gg[i + 1][j + k], mul (add (mul (gg[i][j], f[k]), mul (ff[i][j], g[k])), C(j + k, k)));
            }
        }
    int ans = 0;
    for (int i = 1; i <= m; i++)
        if (n + 1 - m >= i)
            ans = add (ans, mul (gg[i][m], P (n + 1 - m - i, i + 1)));
    printf ("%d\n", ans);
    return 0;
}


#include <bits/stdc++.h>

template <typename T, int NDIMS> struct tensor_view {
	static_assert(NDIMS >= 0, "NDIMS must be nonnegative");

protected:
	std::array<int, NDIMS> shape;
	std::array<int, NDIMS> strides;
	T* data;

	tensor_view(std::array<int, NDIMS> shape_, std::array<int, NDIMS> strides_, T* data_) : shape(shape_), strides(strides_), data(data_) {}

public:
	tensor_view() : shape{0}, strides{0}, data(nullptr) {}

protected:
	int flatten_index(std::array<int, NDIMS> idx) const {
		int res = 0;
		for (int i = 0; i < NDIMS; i++) { res += idx[i] * strides[i]; }
		return res;
	}
	int flatten_index_checked(std::array<int, NDIMS> idx) const {
		int res = 0;
		for (int i = 0; i < NDIMS; i++) {
			assert(0 <= idx[i] && idx[i] < shape[i]);
			res += idx[i] * strides[i];
		}
		return res;
	}

public:
	T& operator[] (std::array<int, NDIMS> idx) const {
		return data[flatten_index(idx)];
	}
	T& at(std::array<int, NDIMS> idx) const {
		return data[flatten_index_checked(idx)];
	}

	template <int D = NDIMS>
	std::enable_if_t<(0 < D), tensor_view<T, NDIMS-1>> operator[] (int idx) const {
		std::array<int, NDIMS-1> nshape; std::copy(shape.begin()+1, shape.end(), nshape.begin());
		std::array<int, NDIMS-1> nstrides; std::copy(strides.begin()+1, strides.end(), nstrides.begin());
		T* ndata = data + (strides[0] * idx);
		return tensor_view<T, NDIMS-1>(nshape, nstrides, ndata);
	}
	template <int D = NDIMS>
	std::enable_if_t<(0 < D), tensor_view<T, NDIMS-1>> at(int idx) const {
		assert(0 <= idx && idx < shape[0]);
		return operator[](idx);
	}

	template <int D = NDIMS>
	std::enable_if_t<(0 == D), T&> operator * () const {
		return *data;
	}

	template <typename U, int D> friend struct tensor_view;
	template <typename U, int D> friend struct tensor;
};

template <typename T, int NDIMS> struct tensor {
	static_assert(NDIMS >= 0, "NDIMS must be nonnegative");

protected:
	std::array<int, NDIMS> shape;
	std::array<int, NDIMS> strides;
	int len;
	T* data;

public:
	tensor() : shape{0}, strides{0}, len(0), data(nullptr) {}

	explicit tensor(std::array<int, NDIMS> shape_, const T& t = T()) {
		shape = shape_;
		strides[NDIMS-1] = 1;
		for (int i = NDIMS-1; i > 0; i--) {
			strides[i-1] = strides[i] * shape[i];
		}
		len = strides[0] * shape[0];
		data = new T[len];
		std::fill(data, data + len, t);
	}

	tensor(const tensor& o) : shape(o.shape), strides(o.strides), len(o.len), data(new T[len]) {
		for (int i = 0; i < len; i++) {
			data[i] = o.data[i];
		}
	}

	tensor& operator=(tensor&& o) noexcept {
		using std::swap;
		swap(shape, o.shape);
		swap(strides, o.strides);
		swap(len, o.len);
		swap(data, o.data);
		return *this;
	}
	tensor(tensor&& o) : tensor() {
		*this = std::move(o);
	}
	tensor& operator=(const tensor& o) {
		return *this = tensor(o);
	}
	~tensor() { delete[] data; }

	using view_t = tensor_view<T, NDIMS>;
	view_t view() {
		return tensor_view<T, NDIMS>(shape, strides, data);
	}
	operator view_t() {
		return view();
	}

	using const_view_t = tensor_view<const T, NDIMS>;
	const_view_t view() const {
		return tensor_view<const T, NDIMS>(shape, strides, data);
	}
	operator const_view_t() const {
		return view();
	}

	T& operator[] (std::array<int, NDIMS> idx) { return view()[idx]; }
	T& at(std::array<int, NDIMS> idx) { return view().at(idx); }
	const T& operator[] (std::array<int, NDIMS> idx) const { return view()[idx]; }
	const T& at(std::array<int, NDIMS> idx) const { return view().at(idx); }

	template <int D = NDIMS>
	std::enable_if_t<(0 < D), tensor_view<T, NDIMS-1>> operator[] (int idx) {
		return view()[idx];
	}
	template <int D = NDIMS>
	std::enable_if_t<(0 < D), tensor_view<T, NDIMS-1>> at(int idx) {
		return view().at(idx);
	}

	template <int D = NDIMS>
	std::enable_if_t<(0 < D), tensor_view<const T, NDIMS-1>> operator[] (int idx) const {
		return view()[idx];
	}
	template <int D = NDIMS>
	std::enable_if_t<(0 < D), tensor_view<const T, NDIMS-1>> at(int idx) const {
		return view().at(idx);
	}

	template <int D = NDIMS>
	std::enable_if_t<(0 == D), T&> operator * () {
		return *view();
	}
	template <int D = NDIMS>
	std::enable_if_t<(0 == D), const T&> operator * () const {
		return *view();
	}
};

template <int& MOD_> struct modnum {
	static constexpr int& MOD = MOD_;
	//static_assert(MOD_ > 0, "MOD must be positive");

private:
	using ll = long long;

	int v;

	static int minv(int a, int m) {
		a %= m;
		assert(a);
		return a == 1 ? 1 : int(m - ll(minv(m, a)) * ll(m) / a);
	}

public:

	modnum() : v(0) {}
	modnum(ll v_) : v(int(v_ % MOD)) { if (v < 0) v += MOD; }
	explicit operator int() const { return v; }
	friend std::ostream& operator << (std::ostream& out, const modnum& n) { return out << int(n); }
	friend std::istream& operator >> (std::istream& in, modnum& n) { ll v_; in >> v_; n = modnum(v_); return in; }

	friend bool operator == (const modnum& a, const modnum& b) { return a.v == b.v; }
	friend bool operator != (const modnum& a, const modnum& b) { return a.v != b.v; }

	modnum inv() const {
		modnum res;
		res.v = minv(v, MOD);
		return res;
	}
	friend modnum inv(const modnum& m) { return m.inv(); }
	modnum neg() const {
		modnum res;
		res.v = v ? MOD-v : 0;
		return res;
	}
	friend modnum neg(const modnum& m) { return m.neg(); }

	modnum operator- () const {
		return neg();
	}
	modnum operator+ () const {
		return modnum(*this);
	}

	modnum& operator ++ () {
		v ++;
		if (v == MOD) v = 0;
		return *this;
	}
	modnum& operator -- () {
		if (v == 0) v = MOD;
		v --;
		return *this;
	}
	modnum& operator += (const modnum& o) {
		v -= MOD-o.v;
		v = (v < 0) ? v + MOD : v;
		return *this;
	}
	modnum& operator -= (const modnum& o) {
		v -= o.v;
		v = (v < 0) ? v + MOD : v;
		return *this;
	}
	modnum& operator *= (const modnum& o) {
		v = int(ll(v) * ll(o.v) % MOD);
		return *this;
	}
	modnum& operator /= (const modnum& o) {
		return *this *= o.inv();
	}

	friend modnum operator ++ (modnum& a, int) { modnum r = a; ++a; return r; }
	friend modnum operator -- (modnum& a, int) { modnum r = a; --a; return r; }
	friend modnum operator + (const modnum& a, const modnum& b) { return modnum(a) += b; }
	friend modnum operator - (const modnum& a, const modnum& b) { return modnum(a) -= b; }
	friend modnum operator * (const modnum& a, const modnum& b) { return modnum(a) *= b; }
	friend modnum operator / (const modnum& a, const modnum& b) { return modnum(a) /= b; }
};

int MOD;

int main() {
	using namespace std;
	ios_base::sync_with_stdio(false), cin.tie(nullptr);
	int N, M; cin >> N >> M >> MOD;
	N++;
	using num = modnum<MOD>;
	vector<num> fact(N+1);
	fact[0] = 1;
	for (int i = 1; i <= N; i++) fact[i] = fact[i-1] * num(i);
	vector<num> ifact(N+1);
	ifact[N] = inv(fact[N]);
	for (int i = N; i >= 1; i--) ifact[i-1] = ifact[i] * num(i);

	vector<num> ways(N+1);
	vector<num> tot_val(N+1);
	ways[0] = 1, tot_val[0] = 0;

	for (int l = 1; l <= N; l++) {
		for (int i = 0; i < l; i++) {
			int a = i, b = l-1-i;

			num choose = fact[a+b] * ifact[a] * ifact[b];
			num sub_ways = ways[a] * ways[b] * choose;
			num sub_val = (tot_val[a] * ways[b] + tot_val[b] * ways[a]) * choose;

			ways[l] += sub_ways * num(l+1);
			tot_val[l] += sub_val * num(l+1) + sub_ways * num(a * (a+1) / 2 + b * (b+1) / 2);
		}
	}

	tensor<num, 2> pref_ways({N+1, M+1});
	tensor<num, 2> pref_vals({N+1, M+1});
	pref_ways[{0,0}] = 1;
	for (int i = 0; i < N; i++) {
		for (int j = 0; j <= M; j++) {
			for (int k = 0; j+k <= M && i+1+k <= N; k++) {
				num choose = fact[j+k] * ifact[j] * ifact[k];
				pref_ways[{i+1+k,j+k}] += pref_ways[{i,j}] * ways[k] * choose;
				pref_vals[{i+1+k,j+k}] += (pref_ways[{i,j}] * tot_val[k] + pref_vals[{i,j}] * ways[k]) * choose;
			}
		}
	}

	cout << pref_vals[{N,M}] << '\n';

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

template <typename A, typename B>
string to_string(pair<A, B> p);

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);

string to_string(const string& s) {
  return '"' + s + '"';
}

string to_string(const char* s) {
  return to_string((string) s);
}

string to_string(bool b) {
  return (b ? "true" : "false");
}

string to_string(vector<bool> v) {
  bool first = true;
  string res = "{";
  for (int i = 0; i < static_cast<int>(v.size()); i++) {
    if (!first) {
      res += ", ";
    }
    first = false;
    res += to_string(v[i]);
  }
  res += "}";
  return res;
}

template <size_t N>
string to_string(bitset<N> v) {
  string res = "";
  for (size_t i = 0; i < N; i++) {
    res += static_cast<char>('0' + v[i]);
  }
  return res;
}

template <typename A>
string to_string(A v) {
  bool first = true;
  string res = "{";
  for (const auto &x : v) {
    if (!first) {
      res += ", ";
    }
    first = false;
    res += to_string(x);
  }
  res += "}";
  return res;
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
  return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
  return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
  return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}

void debug_out() { cerr << endl; }

template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
  cerr << " " << to_string(H);
  debug_out(T...);
}

#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__);

template <typename T>
T inverse(T a, T m) {
  T u = 0, v = 1;
  while (a != 0) {
    T t = m / a;
    m -= t * a; swap(a, m);
    u -= t * v; swap(u, v);
  }
  assert(m == 1);
  return u;
}

template <typename T>
class Modular {
 public:
  using Type = typename decay<decltype(T::value)>::type;

  constexpr Modular() : value() {}
  template <typename U>
  Modular(const U& x) {
    value = normalize(x);
  }

  template <typename U>
  static Type normalize(const U& x) {
    Type v;
    if (-mod() <= x && x < mod()) v = static_cast<Type>(x);
    else v = static_cast<Type>(x % mod());
    if (v < 0) v += mod();
    return v;
  }

  const Type& operator()() const { return value; }
  template <typename U>
  explicit operator U() const { return static_cast<U>(value); }
  constexpr static Type mod() { return T::value; }

  Modular& operator+=(const Modular& other) { if ((value += other.value) >= mod()) value -= mod(); return *this; }
  Modular& operator-=(const Modular& other) { if ((value -= other.value) < 0) value += mod(); return *this; }
  template <typename U> Modular& operator+=(const U& other) { return *this += Modular(other); }
  template <typename U> Modular& operator-=(const U& other) { return *this -= Modular(other); }
  Modular& operator++() { return *this += 1; }
  Modular& operator--() { return *this -= 1; }
  Modular operator++(int) { Modular result(*this); *this += 1; return result; }
  Modular operator--(int) { Modular result(*this); *this -= 1; return result; }
  Modular operator-() const { return Modular(-value); }

  template <typename U = T>
  typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) {
#ifdef _WIN32
    uint64_t x = static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value);
    uint32_t xh = static_cast<uint32_t>(x >> 32), xl = static_cast<uint32_t>(x), d, m;
    asm(
      "divl %4; \n\t"
      : "=a" (d), "=d" (m)
      : "d" (xh), "a" (xl), "r" (mod())
    );
    value = m;
#else
    value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value));
#endif
    return *this;
  }
  template <typename U = T>
  typename enable_if<is_same<typename Modular<U>::Type, int64_t>::value, Modular>::type& operator*=(const Modular& rhs) {
    int64_t q = static_cast<int64_t>(static_cast<long double>(value) * rhs.value / mod());
    value = normalize(value * rhs.value - q * mod());
    return *this;
  }
  template <typename U = T>
  typename enable_if<!is_integral<typename Modular<U>::Type>::value, Modular>::type& operator*=(const Modular& rhs) {
    value = normalize(value * rhs.value);
    return *this;
  }

  Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); }

  template <typename U>
  friend bool operator==(const Modular<U>& lhs, const Modular<U>& rhs);

  template <typename U>
  friend bool operator<(const Modular<U>& lhs, const Modular<U>& rhs);

  template <typename U>
  friend std::istream& operator>>(std::istream& stream, Modular<U>& number);

 private:
  Type value;
};

template <typename T> bool operator==(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value == rhs.value; }
template <typename T, typename U> bool operator==(const Modular<T>& lhs, U rhs) { return lhs == Modular<T>(rhs); }
template <typename T, typename U> bool operator==(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) == rhs; }

template <typename T> bool operator!=(const Modular<T>& lhs, const Modular<T>& rhs) { return !(lhs == rhs); }
template <typename T, typename U> bool operator!=(const Modular<T>& lhs, U rhs) { return !(lhs == rhs); }
template <typename T, typename U> bool operator!=(U lhs, const Modular<T>& rhs) { return !(lhs == rhs); }

template <typename T> bool operator<(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value < rhs.value; }

template <typename T> Modular<T> operator+(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }
template <typename T, typename U> Modular<T> operator+(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) += rhs; }
template <typename T, typename U> Modular<T> operator+(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }

template <typename T> Modular<T> operator-(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T, typename U> Modular<T> operator-(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T, typename U> Modular<T> operator-(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }

template <typename T> Modular<T> operator*(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T, typename U> Modular<T> operator*(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T, typename U> Modular<T> operator*(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }

template <typename T> Modular<T> operator/(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }
template <typename T, typename U> Modular<T> operator/(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) /= rhs; }
template <typename T, typename U> Modular<T> operator/(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }

template<typename T, typename U>
Modular<T> power(const Modular<T>& a, const U& b) {
  assert(b >= 0);
  Modular<T> x = a, res = 1;
  U p = b;
  while (p > 0) {
    if (p & 1) res *= x;
    x *= x;
    p >>= 1;
  }
  return res;
}

template <typename T>
string to_string(const Modular<T>& number) {
  return to_string(number());
}

template <typename T>
std::ostream& operator<<(std::ostream& stream, const Modular<T>& number) {
  return stream << number();
}

template <typename T>
std::istream& operator>>(std::istream& stream, Modular<T>& number) {
  typename common_type<typename Modular<T>::Type, int64_t>::type x;
  stream >> x;
  number.value = Modular<T>::normalize(x);
  return stream;
}

using ModType = int;

struct VarMod { static ModType value; };
ModType VarMod::value;
ModType& md = VarMod::value;
using Mint = Modular<VarMod>;

/*constexpr int md = 1000000009;
using Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>;*/

int n, m;

int main() {
  cin >> n >> m >> md;
  vector<Mint> fact = {1};
  vector<Mint> inv_fact = {1};
  auto C = [&](int x, int y) {
    int sz = max(x, y);
    while((int) fact.size() < sz + 1) {
      fact.push_back(fact.back() * fact.size());
      inv_fact.push_back(1 / fact.back());
    }
    if(y < 0 || y > x) return Mint(0);
    return fact[x] * inv_fact[y] * inv_fact[x - y];
  };
  vector<Mint> ptr_dp(m + 1);
  vector<Mint> ptr_ways(m + 1);
  ptr_ways[0] = 1;
  for(int i = 1; i <= m; i++) {
    for(int j = 0; j < i; j++) {
      int l = j, r = i - 1 - l;
      ptr_ways[i] += ptr_ways[l] * ptr_ways[r] * C(l + r, l) * (l + r + 2);
    }
    for(int j = 0; j < i; j++) {
      int l = j, r = i - 1 - l;
      Mint add = (Mint(l) * (l + 1) + Mint(r) * (r + 1)) / 2;
      ptr_dp[i] += ptr_ways[l] * ptr_ways[r] * C(l + r, l) * add;
      ptr_dp[i] += (ptr_dp[l] * ptr_ways[r] + ptr_dp[r] * ptr_ways[l]) * C(l + r, r) * (l + r + 2);
    }
  }
  vector<vector<Mint>> dp(n + 1, vector<Mint>(m + 1));
  vector<vector<Mint>> ways(n + 1, vector<Mint>(m + 1));
  ways[0][0] = 1;
  for(int i = 1; i <= n; i++) {
    for(int s = 0; s <= min(m, i); s++) {
      if(s == i) {
        dp[i][s] = ptr_dp[s];
        ways[i][s] = ptr_ways[s];
        continue;
      }
      for(int d = 1; d <= s + 1; d++) {
        Mint ft = dp[i - d][s + 1 - d];
        Mint way = ways[i - d][s + 1 - d];
        int add = d - 1;
        ways[i][s] += way * ptr_ways[add] * C(s, add);
        dp[i][s] += (way * ptr_dp[add] + ptr_ways[add] * ft) * C(s, add);
      }
    }
  }
  cout << dp[n][m];
  return 0;
}


#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif

#include <bits/stdc++.h>

using namespace std;

typedef long double ld;

#ifdef DEBUG
#define eprintf(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
#else
#define eprintf(...) ;
#endif

#define sz(x) ((int) (x).size())
#define TASK "text"

const int inf = (int) 1.01e9;
const long long infll = (long long) 1.01e18;
const ld eps = 1e-9;
const ld pi = acos((ld) -1);

#ifdef DEBUG
mt19937 mrand(300);
#else
mt19937 mrand(chrono::steady_clock::now().time_since_epoch().count());
#endif

int rnd(int x) {
  return mrand() % x;
}

void precalc() {
}

const int maxn = 505;
int n, m, mod;

bool read() {
  if (scanf("%d%d%d", &n, &m, &mod) < 3) {
    return false;
  }
  return true;
}

int mul(int a, int b) {
  return (long long) a * b % mod;
}

void add(int &a, int b) {
  a += b;
  if (a >= mod) {
    a -= mod;
  }
}

int c[maxn][maxn];

struct T {
  int cnt, sum;

  T(): cnt(0), sum(0) {}

  T(int x): cnt(x), sum(0) {}

  T(int c, int s): cnt(c), sum(s) {}

  T operator * (const T &t) const {
    int s = mul(cnt, t.sum);
    add(s, mul(sum, t.cnt));
    return T(mul(cnt, t.cnt), s);
  }

  T operator + (const T &t) const {
    int c = cnt;
    add(c, t.cnt);
    int s = sum;
    add(s, t.sum);
    return T(c, s);
  }
};

T dp[maxn];
T pdp[maxn][maxn];

void solve() {
  {
    for (int i = 0; i <= m; ++i) {
      c[i][0] = 1;
      for (int j = 1; j <= i; ++j) {
        c[i][j] = c[i - 1][j - 1];
        add(c[i][j], c[i - 1][j]);
      }
    }
  }
  {
    dp[0] = T(1);
    for (int k = 1; k <= m; ++k) {
      auto &cur = dp[k];
      cur = T(0);
      for (int i = 0; i < k; ++i) {
        auto x = dp[i] * dp[k - i - 1];
        x = x * T(c[k - 1][i]);
        for (int j = 0; j < k; ++j) {
          auto y = x * T(1 + (j == i), abs(i - j));
          cur = cur + y;
        }
      }
      eprintf("%d %d\n", dp[k].cnt, dp[k].sum);
    }
  }
  for (int i = 0; i <= n; ++i) {
    for (int j = 0; j <= m; ++j) {
      pdp[i][j] = T(0);
    }
  }
  pdp[0][0] = T(1);
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j <= m; ++j) {
      auto cur = pdp[i][j];
      if (!cur.cnt && !cur.sum) {
        continue;
      }
      {
        auto &nxt = pdp[i + 1][j];
        nxt = nxt + cur;
      }
      for (int k = 1; j + k <= m && i + k <= n; ++k) {
        auto &nxt = pdp[min(n, i + k + 1)][j + k];
        nxt = nxt + cur * dp[k] * T(c[m - j][k]);
      }
    }
  }
  printf("%d\n", pdp[n][m].sum);
}

int main() {
  precalc();
#ifdef DEBUG
  assert(freopen(TASK ".in", "r", stdin));
  assert(freopen(TASK ".out", "w", stdout));
#endif
  while (read()) {
    solve();
#ifdef DEBUG
    eprintf("Time %.2f\n", (double) clock() / CLOCKS_PER_SEC);
#endif
  }
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define rep(i, a, b) for(int i=(a); i<(b); i++)
#define per(i, a, b) for(int i=(b)-1; i>=(a); i--)
#define sz(a) (int)a.size()
#define de(a) cout << #a << " = " << a << endl
#define dd(a) cout << #a << " = " << a << " "
#define all(a) a.begin(), a.end()
#define pw(x) (1ll<<(x))
#define endl "\n"
typedef double db;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int N = 505;
int n, m, mod;
int C[N][N];
int way[N];
int sum[N];
int g[N][N], f[N][N];
int add(int a, int b){
	if(a + b >= mod) return a + b - mod;
	return a + b;
}
int mul(int a, int b){
	return (ll)a * b % mod;
}
int get(int i){
	return i * (i + 1) / 2;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	//cout << setiosflags(ios::fixed);
	//cout << setprecision(2);
	cin >> n >> m >> mod;
	rep(i, 0, m + 1){
		C[i][0] = 1;
		rep(j, 1, i + 1){
			C[i][j] = add(C[i - 1][j - 1], C[i - 1][j]);
		}
	}
	way[0] = 1;
	rep(i, 1, m + 1){
		rep(j, 0, i){
			way[i] = add(way[i], mul(mul(i + 1, C[i - 1][j]), mul(way[j], way[i - j - 1])));
			sum[i] = add(sum[i], mul(mul(mul(add(get(j), get(i - j - 1)), way[j]), way[i - j - 1]), C[i - 1][j]));
			sum[i] = add(sum[i], mul(mul(i + 1, add(mul(sum[j], way[i - j - 1]), mul(way[j], sum[i - j - 1]))), C[i - 1][j]));
		}
	}
	n ++;
	f[0][0] = 1;
	rep(i, 0, n){
		rep(j, 0, m + 1){
			for(int k = 0; j + k <= m && i + k + 1 <= n; k ++){
				f[i + k + 1][j + k] = add(f[i + k + 1][j + k], mul(mul(f[i][j], way[k]), C[j + k][j]));
				g[i + k + 1][j + k] = add(g[i + k + 1][j + k], mul(add(mul(f[i][j], sum[k]), mul(g[i][j], way[k])), C[j + k][j]));
			}
		}
	}
	cout << g[n][m] << endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int N = 577;
int n, m, Mod, dp[N], dp2[N], C[N][N], res[N][N], res2[N][N];
inline int GetSum(int l, int r)
{
    return ((l + r) * 1LL * (r - l + 1) / 2) % Mod;
}
int main()
{
    scanf("%d%d%d", &n, &m, &Mod);
    for (int i = C[0][0] = 1; i < N; i ++)
        for (int j = C[0][i] = C[i][i] = 1; j < i; j ++)
            C[j][i] = (C[j][i - 1] + C[j - 1][i - 1]) % Mod;
    dp[0] = 1; dp2[0] = 0;
    for (int len = 1; len <= n; len ++)
    {
        for (int i = 1; i <= len; i ++)
        {
            int sm = GetSum(1, i - 1) + GetSum(1, len - i);
            int cnt = len + 1;
            dp[len] = (dp[len] + dp[i - 1] * 1LL * cnt % Mod * dp[len - i] % Mod * C[i - 1][len - 1]) % Mod;
            dp2[len] = (dp2[len] + sm * 1LL * dp[i - 1] % Mod % Mod * dp[len - i] % Mod * C[i - 1][len - 1]) % Mod;
            dp2[len] = (dp2[len] + dp2[i - 1] * 1LL * cnt % Mod * dp[len - i] % Mod * C[i - 1][len - 1]) % Mod;
            dp2[len] = (dp2[len] + dp2[len - i] * 1LL * cnt % Mod * dp[i - 1] % Mod * C[i - 1][len - 1]) % Mod;
        }
    }

    for (int i = 1; i <= n; i ++)
        for (int j = 0; j <= m && j <= i; j ++)
        {
            res[i][j] = res[i - 1][j];
            res2[i][j] = res2[i - 1][j];
            for (int h = 1; h < j; h ++)
            {
                res[i][j] = (res[i][j] + res[i - h - 1][j - h] * 1LL * dp[h] % Mod * C[h][j]) % Mod;
                res2[i][j] = (res2[i][j] + res2[i - h - 1][j - h] * 1LL * dp[h] % Mod * C[h][j]) % Mod;
                res2[i][j] = (res2[i][j] + res[i - h - 1][j - h] * 1LL * dp2[h] % Mod * C[h][j]) % Mod;
            }
            res[i][j] = (res[i][j] + dp[j]) % Mod;
            res2[i][j] = (res2[i][j] + dp2[j]) % Mod;
        }
    return !printf("%d\n", res2[n][m]);
}


#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
int n,m,mod;
int g[505],sg[505];
int f[505][505],sf[505][505];
namespace usual{
	int C[505][505];
	int add(int ta,int tb){ return ta+tb>=mod?ta+tb-mod:ta+tb; }
	int sub(int ta,int tb){ return ta<tb?ta-tb+mod:ta-tb; }
	void make_C(){
		C[0][0]=1;
		for(int i=1;i<=n;i++){
			C[i][0]=1;
			for(int j=1;j<=i;j++)
				C[i][j]=add(C[i-1][j],C[i-1][j-1]);
		}
	}
}
using namespace usual;
int S1(int tn){
	return 1ll*tn*(tn+1)/2%mod;
}
int main(){
	scanf("%d %d %d",&n,&m,&mod);
	make_C();
	g[0]=1;
	for(int i=1;i<=m;i++){
		for(int j=1;j<=i;j++){
			int tmp=1ll*g[j-1]*g[i-j]%mod*C[i-1][j-1]%mod;
			g[i]=add(g[i],1ll*tmp*(i+1)%mod);
			sg[i]=add(sg[i],1ll*sg[j-1]*g[i-j]%mod*C[i-1][j-1]%mod*(i+1)%mod);
			sg[i]=add(sg[i],1ll*sg[i-j]*g[j-1]%mod*C[i-1][j-1]%mod*(i+1)%mod);
			sg[i]=add(sg[i],1ll*tmp*add(S1(i-j),S1(j-1))%mod);
		}
	}
	for(int i=0;i<=n;i++) f[i][0]=1;
	for(int i=1;i<=n;i++){
		if(i<=m) f[i][i]=g[i],sf[i][i]=sg[i];
		for(int j=1;j<=min(i-1,m);j++){
			for(int t=i;t;t--){
				if(i-t>j) break;
				int tmp=1ll*g[i-t]*C[j][i-t]%mod;
				f[i][j]=add(f[i][j],1ll*f[t-1][j-i+t]*tmp%mod);
				sf[i][j]=add(sf[i][j],1ll*sf[t-1][j-i+t]*tmp%mod);
				sf[i][j]=add(sf[i][j],1ll*f[t-1][j-i+t]*sg[i-t]%mod*C[j][i-t]%mod);
			}
		}
	}
	printf("%d\n",sf[n][m]);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 505;
int n, m, mod;
inline int add(int x, int y) {
	x += y;
	return x >= mod ? x - mod : x;
}
inline int mul(int x, int y) { return 1ll * x * y % mod; }
int C[maxn][maxn];
int f[maxn], g[maxn];
int F[maxn][maxn], G[maxn][maxn];
int main() {
	scanf("%d%d%d", &n, &m, &mod);
	for(int i = 0; i <= n; i++) {
		C[i][0] = 1;
		for(int j = 1; j <= i; j++) C[i][j] = add(C[i - 1][j - 1], C[i - 1][j]);
	}
	f[0] = 1;
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= i; j++) {
			f[i] = add(f[i], mul(mul(f[j - 1], f[i - j]), mul(i + 1,  C[i - 1][j - 1])));
			g[i] = add(g[i], mul(mul(f[j - 1], g[i - j]), mul(i + 1,  C[i - 1][j - 1])));
			g[i] = add(g[i], mul(mul(g[j - 1], f[i - j]), mul(i + 1,  C[i - 1][j - 1])));
			g[i] = add(g[i], mul(mul(f[j - 1], f[i - j]), mul(add(C[j][2], C[i - j + 1][2]),  C[i - 1][j - 1])));
		}
	}
	F[0][0] = 1;
	for(int i = 1; i <= n; i++) {
		F[i][i] = f[i], G[i][i] = g[i];
		for(int j = 0; j <= min(i - 1, m); j++) {
			for(int l = 0; l <= j; l++) {
				F[i][j] = add(F[i][j], mul(mul(f[l], F[i - l - 1][j - l]), C[j][l]));
				G[i][j] = add(G[i][j], mul(mul(g[l], F[i - l - 1][j - l]), C[j][l]));
				G[i][j] = add(G[i][j], mul(mul(f[l], G[i - l - 1][j - l]), C[j][l]));
			}
		}
	}
	cout << G[n][m] << endl;
	return 0;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int mod;
inline int addmod(int x)
{
	return x>=mod?x-mod:x;
}
inline int submod(int x)
{
	return x<0?x+mod:x;
}
int fpow(int x,int y)
{
	int ans=1;
	while(y)
	{
		if(y&1) ans=1ll*ans*x%mod;
		x=1ll*x*x%mod;
		y/=2;
	}
	return ans;
}
struct pt
{
	int f,g;
	pt(int f=0,int g=0):f(f),g(g){}
};
pt operator+(const pt x,const pt y)
{
	return pt(addmod(x.f+y.f),addmod(x.g+y.g));
}
pt operator*(const pt x,const pt y)
{
	return pt(1ll*x.f*y.f%mod,addmod(1ll*x.f*y.g%mod+1ll*x.g*y.f%mod));
}
int n,m,pn=1e5,fr[100005],infr[100005],inv[100005];
pt dp[1005],up[1005][1005];
int F(int x)
{
	return 1ll*x*(x+1)/2%mod;
}
int main()
{
	scanf("%d%d%d",&n,&m,&mod);
	fr[0]=infr[0]=1;
	for(int i=1;i<=pn;i++)
	{
		fr[i]=1ll*i*fr[i-1]%mod;
		infr[i]=fpow(fr[i],mod-2);
		inv[i]=fpow(i,mod-2);
	}
	dp[0]=pt(1,0);
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=i;j++)
		{
			pt nw=dp[j-1]*dp[i-j];
			nw.g=addmod(1ll*nw.g*(i+1)%mod+1ll*nw.f*addmod(F(j-1)+F(i-j))%mod);
			nw.g=1ll*nw.g*inv[i]%mod;
			nw.f=1ll*nw.f*(i+1)%mod*inv[i]%mod;
			dp[i]=dp[i]+nw;
		}
	//	printf("i=%d,dp=%lld,%lld\n",i,1ll*dp[i].f*fr[i]%mod,1ll*dp[i].g*fr[i]%mod);
	}
	up[0][0]=pt(1,0);
	for(int i=1;i<=n;i++)
		for(int j=0;j<=min(i,m);j++)
		{
			if(i==j) up[i][j]=dp[i];
			for(int k=0;k<=j&&k<i;k++)
				up[i][j]=up[i][j]+dp[k]*up[i-k-1][j-k];
		}
	int ans=1ll*up[n][m].g*fr[m]%mod;
	printf("%d\n",ans);
	return 0;
}


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define __builtin_ctz __builtin_ctzll
#define __builtin_clz __builtin_clzll
#define __builtin_popcount __builtin_popcountll
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',') { cerr<<*sdbg++; } cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }
template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }
template<class L, class R> ostream& operator<<(ostream& out, map<L, R> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }
int M;
int spow(int a, int b) {
  int r = 1;
  while (b) {
    if (b % 2) {
      r = r * a % M;
    }
    a = a * a % M;
    b /= 2;
  }
  return r;
}
int Inv(int a) {
  int b = M - 2;
  int r = 1;
  while (b) {
    if (b % 2) {
      r = r * a % M;
    }
    a = a * a % M;
    b /= 2;
  }
  return r;
}
int f(int c, int p) {
  if (p == 0) { return 1; }
  return spow(c + 1, p - 1) * (c + 1 - p) % M;
}
const int N = 515;
int newt[N][N];
int inv_newt[N][N];
int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int c, p;
  cin>>c>>p>>M;
  REP (i, c + 2) {
    newt[i][i] = newt[i][0] = 1;
    RE (j, i - 1) {
      newt[i][j] = (newt[i - 1][j] + newt[i - 1][j - 1]) % M;
    }
  }
  debug(newt[10][5]);
  REP (i, c + 2) {
    REP (j, c + 2) {
      inv_newt[i][j] = Inv(newt[i][j]);
    }
  }
  int ans = f(c, p);
//   int ans = (c + 1 - p);
//   RE (i, p - 1) {
//     ans = ans * (c + 1) % M;
//   }
//   RE (i, p) {
//     ans = ans * 2 % M;
//   }
  debug(ans);
  ans = ans * spow(2, p) % M;
  int sum_e = 0;
  RE (i, p) {
    int e = 0;
//     RE (j, i - 1) {
//       e = (e + newt[c + 1 - j][i - 1 - j] * inv_newt[c + 1][i - 1]) % M;
//     }
    RE (w, i - 1) {
      int zioms = newt[i - 1][w] * f(w, w) % M * f(c - w - 1, i - 1 - w) % M;
      debug(zioms, i, w);
      zioms = zioms * Inv(spow(c + 1, i - 1)) % M;

      // zioms - pstwo, ze na ustalony pzedzial [l, r] jest zapelniony, a po jego bokach nie
      e = (e + w * (w + 1) / 2 * zioms) % M;
    }
    debug(i, e, e * ans % M);
    sum_e = (sum_e + e) % M;
  }
  cout<<ans * sum_e % M<<"\n";

  return 0;
}


//CLOCKS_PER_SEC
using namespace std;
#include<bits/stdc++.h>
#define sqr(x) 1ll*(x)*(x)
//#define sort stable_sort
#define ll long long
#define mk make_pair
#define pb push_back
#define in insert
#define mtr(x,y,z) mk(mk(x,y),z)
#define fi first
#define se second
#define lch(x) ((x)<<1)
#define rch(x) (((x)<<1)|1)
#define all(x) (x).begin(),(x).end()
#define titose CLOCKS_PER_SEC
#define fpi(x) freopen(x,"r",stdin);
#define fpo(x) freopen(x,"w",stdout);
#define fprio fpi("in.txt");fpo("out.txt");
#define fast ios_base::sync_with_stdio(false);
inline void read(int &x){int v=0,f=1;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=(c&15);while (isdigit(c=getchar())) v=(v<<1)+(v<<3)+(c&15);x=v*f;}
inline void read(ll &x){ll v=0ll,f=1ll;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=(c&15);while (isdigit(c=getchar())) v=(v<<1)+(v<<3)+(c&15);x=v*f;}
inline void readc(char &x){char c;while (((c=getchar())==' ')||c=='\n');x=c;}
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vi vector<int>
#define vl vector<ll>
#define si set<int>
#define sl set<ll>
#define mii map<int,int>
#define mll map<ll,ll>
#define msi map<string,int>
#define msl map<string,ll>
#define piii pair<int,pii >
#define piipi pair<pii,int>
#define plll pair<ll,pll >
#define pllpl pair<pll,ll>
#define pqi priority_queue<int>
#define pql priority_queue<ll>
#define npqi priority_queue<int,vector<int>,greater<int> >
#define npql priority_queue<ll,vector<ll>,greater<ll> >
#define forup(i,a,b) for ((i)=(a);(i)<=(b);(i)++)
#define fordo(i,a,b) for ((i)=(a);(i)>=(b);(i)--)
#define rep(i,x) forup ((i),1,(x))
#define repd(i,x) fordo ((i),(x),1)
#define rep0(i,x) forup ((i),0,((int)(x))-1)
#define rep0d(i,x) fordo ((i),((int)(x))-1,0)
#define itr iterator
#define fe(itcalc,c) for(__typeof((c).begin()) itcalc=(c).begin();itcalc!=(c).end();itcalc++)
#define NO {cout<<"NO";return 0;}
#define YES {cout<<"YES";return 0;}
#define y0 y000000000000000000000000000
#define y1 y111111111111111111111111111
#define j0 j000000000000000000000000000
#define j1 j111111111111111111111111111
#define cl0(a) memset((a),(0),(sizeof((a))))
#define clz(a) memset((a),(0x16),(sizeof((a))))
#define clf(a) memset((a),(-(0x16)),(sizeof((a))))
#define inf 0x3bbbbbbb
#define lnf 0x2bbbbbbbbbbbbbbbll
//#define sqrt divi
#define p2(i) (1ll<<(i))
#define readi read
#define readll read
/*************************************************/
int mod,n,m,i,j,k,c[505][505],f[505],g[505],dp[505][505][2],ans;
int main()
{
	read(n);read(m);read(mod);
	c[0][0]=1;rep(i,n){c[i][0]=1;rep(j,i)c[i][j]=(c[i-1][j]+c[i-1][j-1])%mod;}
	f[0]=1;
	rep(i,n){
		rep0(j,i){
			k=i-j-1;
			f[i]=(f[i]+1ll*f[j]*f[k]%mod*(i+1)%mod*c[i-1][j])%mod;
			g[i]=(g[i]+1ll*g[j]*f[k]%mod*(i+1)%mod*c[i-1][j])%mod;
			g[i]=(g[i]+1ll*f[j]*g[k]%mod*(i+1)%mod*c[i-1][j])%mod;
			g[i]=(g[i]+1ll*f[j]*f[k]%mod*c[i-1][j]%mod*((j*(j+1)/2)+(k*(k+1)/2)))%mod;
		}
	}
	dp[0][0][1]=1;
	rep0(i,n){
		rep0(j,i+1){
			dp[i+1][j][1]=(0ll+dp[i+1][j][1]+dp[i][j][0]+dp[i][j][1])%mod;
			rep(k,n-i){
				dp[i+k][j+k][0]=(dp[i+k][j+k][0]+1ll*dp[i][j][1]*f[k]%mod*c[j+k][j])%mod;
			}
		}
	}
	rep(j,n)rep(i,j){
		int rem=m-(j-i+1);
		if(rem<0) continue;
		rep0(k,rem+1){
			ans=(ans+1ll*g[j-i+1]*dp[i-1][k][1]%mod*dp[n-j][rem-k][1]%mod*c[m][rem]%mod*c[rem][k])%mod;
		}
	}
	cout<<ans<<endl;
	return 0;
}


#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <list>
#include <cassert>
#include <climits>
#include <bitset>
#include <chrono>
#include <random>
using namespace std;

#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) FORE(i,0,n)
#define FORSZ(i,a,v) FOR(i,a,SZ(v))
#define REPSZ(i,v) REP(i,SZ(v))
std::mt19937 rnd((int)std::chrono::steady_clock::now().time_since_epoch().count());
typedef long long ll;
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }

const int MAXCOMP = 500;
const int MAXPERS = MAXCOMP;
struct Res { int ways, summaddness; Res() {} Res(int ways, int summaddness) :ways(ways), summaddness(summaddness) {} };

int ncomp, npers, MOD;
int choose[MAXCOMP + 1][MAXCOMP + 1];

int calcsum(int l, int r) { return (l + r) * (r - l + 1) / 2; }

bool done2[MAXCOMP + 1];
Res mem2[MAXCOMP + 1];

// no empty
Res go2(int n) {
	if (n == 1) return Res(2, 0);
	if (done2[n]) return mem2[n];
	Res ret(0, 0);
	REP(i, n) {
		int lcnt = i, rcnt = n - i - 1;
		Res lres = lcnt == 0 ? Res(1, 0) : go2(lcnt);
		Res rres = rcnt == 0 ? Res(1, 0) : go2(rcnt);
		int mways = (lcnt + 1) + (rcnt + 1);
		int msummaddness = calcsum(0, lcnt) + calcsum(0, rcnt);
		int mlt = choose[lcnt + rcnt][lcnt];
		ret.ways = (ret.ways + (ll)lres.ways * mways % MOD * rres.ways % MOD * mlt) % MOD;
		ret.summaddness = (ret.summaddness + (ll)lres.summaddness * mways % MOD * rres.ways % MOD * mlt + (ll)lres.ways * msummaddness % MOD * rres.ways % MOD * mlt + (ll)lres.ways * mways % MOD * rres.summaddness % MOD * mlt) % MOD;
	}
	//printf("go2(%d..%d): ways=%d summaddness=%d\n", l, r, ret.ways, ret.summaddness);
	done2[n] = true, mem2[n] = ret;
	return ret;
}

bool done1[MAXCOMP][MAXPERS + 1];
Res mem1[MAXCOMP][MAXPERS + 1];

// with empty
Res go1(int at, int cnt) {
	if (ncomp - at == cnt) return go2(cnt);
	if (done1[at][cnt]) return mem1[at][cnt];
	Res ret(0, 0);
	FOR(i, at, ncomp) {
		int lcnt = i - at;
		int rcnt = cnt - lcnt;
		if (rcnt<0 || rcnt>ncomp - i - 1) continue;
		Res lres = i == at ? Res(1, 0) : go2(lcnt);
		Res rres = i + 1 == ncomp ? Res(1, 0) : go1(i + 1, rcnt);
		int mlt = choose[lcnt + rcnt][lcnt];
		//printf("\tgo1(%d..%d): %d -> lres=(%d,%d) rres=(%d,%d) mlt=%d\n", at, cnt, i, lres.ways, lres.summaddness, rres.ways, rres.summaddness, mlt);
		ret.ways = (ret.ways + (ll)lres.ways * rres.ways % MOD * mlt) % MOD;
		ret.summaddness = (ret.summaddness + (ll)lres.summaddness * rres.ways % MOD * mlt + (ll)lres.ways * rres.summaddness % MOD * mlt) % MOD;
	}
	//printf("go1(%d..%d): ways=%d summaddness=%d\n", at, cnt, ret.ways, ret.summaddness);
	done1[at][cnt] = true, mem1[at][cnt] = ret;
	return ret;
}

int solve() {
	REPE(i, ncomp) { choose[i][0] = choose[i][i] = 1; FOR(j, 1, i) choose[i][j] = (choose[i - 1][j - 1] + choose[i - 1][j]) % MOD; }
	REPE(i, ncomp) done2[i] = false;
	REP(i, ncomp) REPE(j, npers) done1[i][j] = false;
	return go1(0, npers).summaddness;
}

void run() {
	scanf("%d%d%d", &ncomp, &npers, &MOD);
	printf("%d\n", solve());
}

int main() {
	run();
	return 0;
}


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

template<class TH> void _dbg(const char *sdbg, TH h) { cerr<<sdbg<<'='<<h<<endl; }
template<class TH, class... TA> void _dbg(const char *sdbg, TH h, TA... a) {
  while(*sdbg!=',')cerr<<*sdbg++;
  cerr<<'='<<h<<','; _dbg(sdbg+1, a...);
}
template<class T> ostream &operator<<(ostream& os, vector<T> V) {
  os << "["; for (auto vv : V) os << vv << ","; return os << "]";
}
template<class L, class R> ostream &operator<<(ostream &os, pair<L, R> P) {
  return os << "(" << P.first << "," << P.second << ")";
}
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)

/*...................................................*/

vector<long long> a;
long long fn(long long n, long long l) {
	long long num = n / a[l];
	n %= a[l];
  if(!n) {
    return num * l;
  }
  return num * l + min(l + fn(a[l] - n, l - 1), fn(n, l - 1));
}
main() {
  ios::sync_with_stdio(false), cin.tie(0);

  long long t = 1, n, m, i, j, k, u, to, w;
  // cin >> t;
  // long long tc = t;
  m = 0;
  while(a.size() < 17) {
    a.push_back(m);
    m = m * 10 + 1;
  }
  while (t--) {
    // cout << "Case #" << tc - t << ": ";
    cin >> n;
    cout << fn(n, 16);
  }
}


#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;

int n,ans=0x3f3f3f3f;
long long mul[100];

void dfs(int now,long long num,int opt)
{
    //cout<<now<<' '<<num<<' '<<opt<<endl;
    if(num==0){ans=min(ans,opt);return;}
    if(now==-1)return;
    int i,j,k;
    for(i=-10;i*mul[now]<=num;i++);
    dfs(now-1,num-(i-1)*mul[now],opt+abs(i-1)*(now+1));
    dfs(now-1,num-i*mul[now],opt+abs(i)*(now+1));
}

int main()
{
    int i,j,k;mul[0]=1;long long num;
    cin>>num;
    for(i=1;i<=18;i++)mul[i]=mul[i-1]*10;
    for(i=1;i<=18;i++)mul[i]+=mul[i-1];
    for(i=1;mul[i]<=num;i++);
    n=i;
    dfs(n,num,0);
    cout<<ans<<endl;
    return 0;
}


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

#define LL __int64

using namespace std;

LL n;
LL an;

void dfs(LL x,LL m){
	if(m>an) return;
	if(!x){
		an=m;
		return;
	}
	LL tmp=0,st=0;
	while(tmp*10+1<=x) tmp=tmp*10+1,st++;
	dfs(x%tmp,m+x/tmp*st);
	dfs(tmp*10+1-x,m+st+1);
}

int main()
{
	an=1e9;
	cin>>n;
	dfs(n,0);
	cout<<an<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
long long pw[20];
int ans;
long long check(long long x,int &len) {
	len=0;
	while(x>=10) {
		x/=10;
		len++;
	}
	return x;
}
void dfs(long long x,int cnt) {
	//printf("%lld %d\n",x,cnt);
	if(cnt>=ans)return;
	if(x==0) {
		ans=cnt;
		return;
	}
	int len;
	int t=check(x,len);
	//��
	dfs(abs(x-pw[len]*t),cnt+t*(len+1));
	if(t-1>0)dfs(abs(x-pw[len]*(t-1)),cnt+(t-1)*(len+1));
	if(t>1)dfs(abs(pw[len+1]-x),cnt+(len+2));
}
int main() {
	long long n;
	scanf("%lld",&n);
	pw[0]=1;
	for(int i=1; i<=18; i++) {
		pw[i]=pw[i-1]*10+1;
		//printf("%lld\n",pw[i]);
	}
	ans=1e9;
	dfs(n,0);
	printf("%d\n",ans);
	return 0;
}


#include <algorithm>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <vector>
#include <math.h>
#include <queue>
#include <set>
#include <map>

using namespace std;
long long n;
int sol=1e9;
void dfs(long long n,int cost){
if(cost>=sol)return;
if(!n){
sol=cost;
return;
}
long long s=1,c=1;
while(s*10+1<=n)s=s*10+1,c++;
dfs(n%s,cost+c*(n/s));
dfs(s*10+1-n,cost+c+1);
}
int main() {
 //freopen("test.in","r",stdin);
 cin>>n;
 dfs(n,0);
 cout<<sol;
 return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
#define LL long long
using namespace std;

LL res = 0;
int num(LL n){
   int num = 0;
    while(n){
        n /= 10;
        num++;
    }
    return num;
}

//same
LL find(LL n){
    int ex = num(n);
    LL cur = 0, ad = 1;
    for(int i = 0; i <= ex-1; i++){
            cur += ad;
            ad *= 10;
    }
    if(cur <= n) return cur;
    return ((cur-1)/10);
}

LL process(LL n){
 //   cout<<n<<endl;
    if(n <= 6){
        return n;
    }
    if(n <= 11) return (13 - n);
    LL tmp = find(n);
    LL more = tmp*10+1;
    if(n % tmp == 0){
         LL t = n / tmp;
         if(n <= more/2 + tmp) return num(tmp)*t;
         else{
              LL cur = process(more - n);
              return num(more) + cur;
         }
    }
    else{
        LL _m = (n / tmp)*tmp;
        LL _M = (n / tmp + 1)*tmp;
        LL res = process(_m) + process(n - _m);
        if(n > more/2) res = min(process(_m) + process(n - _m), num(more) + process(more-n));
        return res;
    }
}
int main(){
    LL n;
    cin>>n;
//    for(int i = 1; i <= n; i++) cout<<i<<" "<<process(i)<<endl;
    cout<<process(n)<<endl;
//    system("PAUSE");
    return 0;
}


#include <iostream>
#include <cstring>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#define _USE_MATH_DEFINES
#include <math.h>
#include <cstdlib>
#include <algorithm>
#include <assert.h>
using namespace std;

void smain();
int main(){
    ios_base::sync_with_stdio(0);
#ifdef DEBUG
    freopen("input.txt","rt",stdin);
#endif
    smain();
    return 0;
}

#define forn(i,n) for (int i=0;i<n;i++)
#define rforn(i,n) for (int i=n-1;i>=0;i--)
#define fori(i,a) for(auto i=a.begin(); i!=a.end(); ++i)
#define rfori(i,a) for(auto i=a.rbegin(); i!=a.rend(); ++i)
#define int long long
#define mp(a,b) make_pair(a,b)
#define INF 0x7fffffff
#define MOD 1000000007
#define EPS 0.00000001
#define N 10000
/* --------- END TEMPLATE CODE --------- */

int p[17], n;

int solve(int n, int len) {
    return n / p[len] * len + (n % p[len] ? min(solve(n % p[len], len-1), len + solve(p[len] - n % p[len], len - 1)) : 0);
}

void smain(){
    for(int i=1; i<17; ++i) p[i] = p[i - 1] * 10 + 1;
    cin >> n;
    cout << solve(n, 16);
}


#include <bits/stdc++.h>

using namespace std;

#define inf (ll)1e15
#define ll long long
#define all(x) x.begin(), x.end()
#define x first
#define y second

const int N = 200010;

const int mod = (int)1e9 + 7;
const int MX = 1000010;

std::vector<ll> ones({0ll});

int ans = MX;

void bst(ll x, int vv){

	if(vv > ans)
		return;

	if(x == 0){
		ans = vv;
		return;
	}

	auto lb = lower_bound(all(ones), x);
	auto ub = upper_bound(all(ones), x);

	if(lb == ub) lb--;

	ll rem = x - *lb;
	int cost = lb - ones.begin();
	ll rem2 = *ub - x;

	// cout << x << " " << vv << endl;

	bst(x % *lb, vv + cost * (x / *lb));
	bst(rem2, vv + cost + 1);
}

int main(){

    cin.tie(0);
    cin.sync_with_stdio(0);

    #ifdef Cyborg101
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif

    ll n;
    cin >> n;

    for(int i = 1; i <= 16; ++i){
    	ones.push_back(ones.back() * 10 + 1);
    }

	bst(n, 0);

    cout << ans << endl;

  	return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <complex>
#include <ext/pb_ds/assoc_container.hpp>
#include <bitset>
#include <unordered_set>
#include <random>
using namespace std;
using namespace __gnu_pbds;
long long A[20];
long long dfs(int ind, long long n) {
	if(ind == 0)
		return n == 0 ? 0 : 1e8;
	if(n < 0) n = -n;
	auto m = n / A[ind];
	return min(dfs(ind-1, n - m * A[ind]) + m * ind,
				dfs(ind-1, n - (m+1) * A[ind]) + (m + 1) * ind);
}
int main() {
	ios::sync_with_stdio(0); cin.tie(0);
	long long n;
	cin >> n;
	for(int i = 1; i <= 16; ++i)
		A[i] = A[i-1] * 10 + 1;
	cout << dfs(16, n) << '\n';
    return 0;
}


//In the name of God

#include <iostream>
using namespace std;
#define lol long long
lol a[20];

lol solve(lol n)
{
  //cerr<<n<<endl;
  if(n==0)
    return 0;
  int ind=0;
  for(int i=1;i<=16;i++)
    if(a[i]>n)
      {
	ind=i;
	break;
      }
  //cerr<<a[ind-1]<<" ";
  lol ans1=1e18,ans2=1e18;
  ans1=n/a[ind-1]*(ind-1)+solve(n%a[ind-1]);
  if(a[ind]-n<n)
    ans2=ind+solve(a[ind]-n);
  return min(ans1,ans2);
}

int main()
{
  for(int i=1;i<=16;i++)
    a[i]=a[i-1]*10ll+1ll;
  lol n;
  cin>>n;
  cout<<solve(n)<<endl;
  return 0;
}


#include <bits/stdc++.h>

#define dbg(x) cerr << #x << " = " << (x) << endl
#define raya cerr << "-------------------" << endl

using namespace std;

typedef long long ll;

struct step {
	ll val; int cost;
	bool operator<(const step &c) const {
		return c.cost < cost;
	}
};

set<ll> visited;

bool wasVisited(ll c) {
	return visited.find(c) != visited.end();
}

step uupper(ll n){
	ll res = 0;
	int i = 0;
	while(res<n){
		res*=10;
		res++;
		i++;
	}
	return {res, i};
}

step upper(ll n){
	ll res = 0;
	int i = 0;
	while(res*10+1<=n){
		res*=10;
		res++;
		i++;
	}
	ll resmul = res;
	int imul = i;
	while(res < n){
		res+=resmul;
		i+=imul;
	}
	return {res, i};
}

step lower(ll n){
	ll res = 0;
	int i = 0;
	while(res*10+1<=n){
		res*=10;
		res++;
		i++;
	}
	ll resmul = res;
	int imul = i;
	while(res+resmul <= n){
		res+=resmul;
		i+=imul;
	}
	return {res, i};
}

int main(int argc, char **argv) {
	ll n;
	cin >> n;

	priority_queue<step> pq;

	pq.push(step{n, 0});

	while(pq.top().val != 0){
		ll val = pq.top().val;
		int cost = pq.top().cost;
		pq.pop();

		if(wasVisited(val))
			continue;
		visited.insert(val);

		for (step next : { lower(val), upper(val), uupper(val) }) {
			next.cost += cost;
			next.val = abs(val - next.val);
			pq.push(next);

		}

	}

	cout << pq.top().cost << endl;
}


#include<iostream>
#include<cstdio>
using namespace std;

#define ll long long

ll n,m,tmp[20];

ll Min(ll a,ll b) {if(a<b) return a;  return b;}

ll DFS(ll n,int x)
{
     if(n<0) n=-n;
     ll r=n/tmp[x]*x;
     n=n-n/tmp[x]*tmp[x];
     if(n==0) return r;
     return r+Min(DFS(n,x-1),x+DFS(tmp[x]-n,x-1));
}

int main()
{
    int i;
    tmp[1]=1;
    for(i=2;i<=18;i++) tmp[i]=tmp[i-1]*10+1;
    cin>>n;
    //for(i=1;i<=16;i++) cout<<tmp[i]<<endl;
    m=DFS(n,17);
    cout<<m;
    return 0;
}


#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll use[17];
int dfs(ll n,int di)
{
    int res=(n/use[di])*di;
    n=n%use[di];
    if(!n) return res;
    return res+min(dfs(use[di]-n,di-1)+di,dfs(n,di-1));
}
int main()
{
    for(int i=1;i<=16;i++) use[i]=use[i-1]*10+1;
    ll n;
    cin>>n;
    printf("%d\n",dfs(n,16));
    return 0;
}


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cmath>
#define L 18
typedef long long ll;
using namespace std;

ll a[L];

int dfs(ll n, int p) {
	int k = n / a[p];
	n = n % a[p];

	if (n == 0)
		return p * k;
	return p * k + min(p + dfs(a[p] - n, p - 1), dfs(n, p - 1));
}

int main() {
	a[0] = 0;
	for (int i = 1; i < L; i++)
		a[i] = a[i-1] * 10 + 1;

	ll n;
	while (cin >> n) {
		cout << dfs(n, L-1) << endl;
	}
}


//template igorjan94 version from 21 may 2014
#include <bits/stdc++.h>

#define pb push_back
#define ll long long
#define forit(it, r) for (auto it = r.begin(); it != r.end(); it++)
#define forn(i, n) for (int i = 0; i < n; i++)
#define forn1(i, n) for (int i = 1; i < n; i++)
#define fori(n) for (int i = 0; i < n; i++)
#define forj(n) for (int j = 0; j < n; j++)
#define vi vector<int>
#define vll vector<long long>
#define pii pair<int, int>
#ifndef ONLINE_JUDGE
#define lld I64d
#endif
#define FILENAME "input"
#define INF 1000000007

using namespace std;

template <class Head, class... Tail> void writeln(Head head, Tail... tail);
template <class Head, class... Tail> void readln(Head& head, Tail&... tail);
void writeln(){printf("\n");}void readln(){}

///----------------------------------------------------------------------------------------------------------------------------

ll n;
ll degs[20], deg[20];

ll rec(ll cur, int d)
{
    cur = abs(cur);
    if (cur % degs[d] == 0)
        return cur / degs[d] * d;
    ll k = cur / degs[d];
    ll temp1 = (k * d + rec(cur - k * degs[d], d - 1));
    ll temp2 = ((k + 1) * d + rec((k + 1) * degs[d] - cur, d - 1));
    return min(temp1, temp2);
}//1111
// -111
// -111
//  889
//  +11
//   -1
//  899

void run()
{
    degs[1] = 1;
    fori(17)
        degs[i + 2] = degs[i + 1] * 10 + 1;
    readln(n);
    writeln(rec(n, 18));
}

int main()
{
//    freopen(FILENAME".in", "r", stdin);
//    freopen(FILENAME".out", "w", stdout);
    run();
    return 0;
}

void print(double a){printf("%f ", a);}
void print(int a){printf("%d ", a);}
void print(string a){printf("%s ", a.c_str());}
void print(long long a){printf("%lld ", a);}
void print(unsigned long a){printf("%ld ", a);}
void print(unsigned int a){printf("%d ", a);}
void print(char a){printf("%c ", a);}
template<class Type>
void print(vector<Type>& a){for(int i = 0; i < a.size(); ++i)print(a[i]);}
template<class Type>
void print(vector<vector<Type>>& a){for(int i = 0; i < a.size(); ++i)writeln(a[i]);}
template<class Type1, class Type2>
void print(pair<Type1, Type2>& a){print(a.first);print(a.second);}
void read(double &a){scanf("%lf", &a);}
void read(int &a){scanf("%d", &a);}
void read(string &a){cin>>a;}
void read(long long &a){scanf("%lld", &a);}
void read(char &a){scanf("%c", &a);}
template<class Type>
void read(vector<Type> &a){if (a.size() == 0){int n; read(n); a.resize(n);}for(int i = 0; i < a.size(); ++i)read(a[i]);}
template<class Type>
void read(vector<vector<Type>> &a){for(int i = 0; i < a.size(); ++i)readln(a[i]);}
template <class Head, class... Tail>
void writeln(Head head, Tail... tail){print(head);writeln(tail...);}
template <class Head, class... Tail>
void readln(Head& head, Tail&... tail){read(head);readln(tail...);}


/*benamekhoda*/
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#define rep(i, n) for(LL i = 0; i < n; i++)
typedef long long LL;
using namespace std;

const LL N=2002002;
LL a[N];
LL ans, sum;

LL solve(LL n)
{
    if (!n) return 0;
    //    cout << n << endl;
    LL j = 1, cnt = 1;
    while (j <= n) {
        j = (j * 10) + 1;
        cnt++;
    }
    cnt--;
    j -= 1; j /= 10;
    if (j == n) return cnt;
    LL best = 1 << 29;
    if (j * 10 + 1 - n < n) best = solve(j * 10 + 1 - n) + cnt + 1;
    LL best2;
    LL i = 1;
    while (j * i <= n)
        best2 = j * i, i++;
    return min(solve(n - best2) + cnt * (i - 1), best);
}

int main()
{
    ios_base::sync_with_stdio(false);
    LL n;
    cin >> n;
    cout << solve(n);
    return 0;
}


#include<cstdint>
#include<iostream>
#include<vector>

int64_t nb_digits(int64_t n) {
  n = n < 0 ? -n : n;
  int64_t digits = 0;
  while (n) {
    ++digits;
    n /= 10;
  }
  return digits;
}

int64_t ones(int64_t n) {
  int64_t res = 0;
  for (int i = 0; i < n; ++i)
    res = 10*res + 1;
  return res;
}

int64_t aux2(int64_t n) {
  if (n == 0) return 0;
  n = n < 0 ? -n : n;
  int64_t d = nb_digits(n);
  return d + aux2(n-ones(d));
}

int64_t aux(int64_t n, int64_t sign, int64_t acc, int64_t max, std::vector<int> &already_in) {
  if (acc >= max) return max;
  if (n == 0) return acc;
  if (n < 0) { n = -n; sign = -sign; }
  int64_t d = nb_digits(n);
  int64_t ones_d = ones(d);
  int64_t res1 = max, res2 = max;

  if (0 <= already_in[d]*sign && -10 < already_in[d] && already_in[d] < 10) {
    already_in[d] += sign;
    res1 = aux(n-ones_d, sign, acc+d, max, already_in);
    already_in[d] -= sign;
  }
  if (0 <= already_in[1+d]*sign && -10 < already_in[1+d] && already_in[1+d] < 10) {
    already_in[d+1] += sign;
    res2 = aux(n-10*ones_d-1, sign, acc+d+1, res1, already_in);
    already_in[d+1] -= sign;
  }
  return res1 < res2 ? res1 : res2;
}

int main(int argc, char* argv[]) {
  int64_t n;
  std::cin >> n;
  std::vector<int> already_in(20, 0);
  std::cout << aux(n, 1, 0, aux2(n), already_in) << std::endl;
  return 0;
}


#include <cstdio>
#include <map>
#include <set>
#include <cstring>
#include <queue>
#include <algorithm>

using namespace std;

long long v;
long long cand[17];

int rec(int ind, long long val) {
	val = abs(val);
	if (ind == 0) {
		return val;
	}
	int a1 = val / cand[ind];
	int a2 = a1+1;
	return min(a1*(ind+1) + rec(ind-1, val-a1*cand[ind]), a2*(ind+1) + rec(ind-1, val-a2*cand[ind]));
}

int main(){
	scanf("%lld",&v);
	cand[0] = 1;
	for(int i = 1; i < 17; i++) {
		cand[i] = cand[i-1]*10 + 1;
	}
	printf("%d\n", rec(16, v));
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
long long int i,n,top,t,k,arr[500000],m=INT_MAX,bs;

void f(long long int x,long long int s,long long int k,long long int kk){
  if(s>=i)
      return ;
  if(x==0){
        printf("%d",s);
        exit(0);
    }
    while(k>x){ k/=10; kk--;}
    f(0,s+((k*10+1)-x)+kk+1,k*10+1,kk+1);
    long long int t=x/k;
    f((k*10+1)-x,s+kk+1,k,kk);
    f(x-(k*t),s+(kk*t),k,kk);

}

int main(){
    scanf("%lld",&n);
    k=1;
    bs=1;
    while(k*10+1<=n){
        k=k*10+1;
        bs++;
    }
    for(i=0;i<n;i++)
        f(n,0,k,bs);
    if(m==INT_MAX) m=min(n,11-n+2);
        printf("%lld",m);

}


#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <functional>
#include <iomanip>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <hash_set>
#include <hash_map>
#include <algorithm>

//define NDEBUG
#include <cassert>

#define FAST_READER ios::sync_with_stdio(false); cin.tie(nullptr);
#define all_(v) (v).begin(), (v).end()
#define for_(i, a, b) for (int i = (a); i < (int)(b); i++)
#define ford_(i, a, b) for (int i = (a); i > (int)(b); i--)
#define foreach_(it,S) for(__typeof((S).begin()) it = (S).begin(); it != (S).end(); it++)
#define sz_(v) ((int)(v).size())
#define mp_ make_pair
#define pb_ push_back
typedef long long LL_;
typedef long double LD_;
template<class T> T sqr_(T a) {return a * a;}
template<class T> T abs_(T a) {return a > 0 ? a : -a;}
template<class T> T sgn_(T a) {return a > 0 ? 1 : (a < 0 ? -1 : 0);}

using namespace std;

long long calc(long long n) {
	if (n == 0) return 0;
	long long k = 0, amt = 0;
	while (k * 10 + 1 <= n) k = k * 10 + 1, ++amt;
	long long res1 = amt * (n / k) + calc(n % k);
	long long res2 = amt + 1;
	n = 10 * k + 1 - n;
	res2 += amt * (n / k) + calc(n % k);
	return min(res1, res2);
}

int main() {

#ifndef ONLINE_JUDGE
	assert(freopen("input.txt", "r", stdin)); assert(freopen("output.txt", "w", stdout));
#endif

	FAST_READER;

	long long n;
	cin >> n;
	cout << calc(n);

	return 0;
}


#include <cstdio>
#include <map>
#include <set>
#include <cstring>
#include <queue>
#include <algorithm>

using namespace std;

long long v;
long long cand[17];

int rec(int ind, long long val) {
    val = abs(val);
    if (ind == 0) {
        return val;
    }
    int a1 = val / cand[ind];
    int a2 = a1+1;
    return min(a1*(ind+1) + rec(ind-1, val-a1*cand[ind]), a2*(ind+1) + rec(ind-1, val-a2*cand[ind]));
}

int main(){
    scanf("%lld",&v);
    cand[0] = 1;
    for(int i = 1; i < 17; i++) {
        cand[i] = cand[i-1]*10 + 1;
    }
    printf("%d\n", rec(16, v));
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL n,A[20],B[20],ans;
#define FOR(i,a,b) for(int i=(a);i<=(b);i++)

void dfs(int pos,LL now,LL res){
//	printf("%d %lld %lld\n",pos,now,res);
	if(res>=ans)return;
	if(pos==0){
		if(!now)ans=res;
		return;
	}
	int t=now/A[pos];
	int d=abs(t)-1;
	if(t<0)d=-d;
	int s=abs(t)+1;
	if(t<0)s=-s;
	// 72 -77 -66
	dfs(pos-1,now-t*B[pos],res+abs(t)*pos);
	dfs(pos-1,now-d*B[pos],res+abs(d)*pos);
	dfs(pos-1,now-s*B[pos],res+abs(s)*pos);
}
int main(){
	FOR(i,1,16)B[i]=B[i-1]*10+1;
	A[1]=1;
	FOR(i,2,16)A[i]=A[i-1]*10;
	scanf("%lld",&n);
	LL m=n;
	int c=0;
	while(m){
		c++;
		m/=10;
	}
	ans=1e18;
	dfs(c,n,0);
	dfs(c,B[c+1]-n,c+1);
	printf("%lld\n",ans);
	return 0;
}


//God & me
/*
    #   #####  TM    #   ###       ####   ####    #####      #     #######  #####     #   #
  # #      #         #  #         #       #   #   #         # #       #     #         #   #
    #     #          #   ##       #  ##   ####    #####    #####      #     #####     #   #
    #    #           #     #      #   #   #   #   #       #     #     #     #
  ####  #            #  ###        ####   #    #  #####  #       #    #     #####     #   #

*/
#include <bits/stdc++.h>
#define pb push_back
#define X first
#define Y second
#define int long long
#define in(a,n) for_each(a,a+n,[](int &x){cin>>x;})
using namespace std;
/*<===LINE==#17#===>*/
template <class T,class L> T& smax(T &x,L y){if(y>x)x=y;return x;}
template <class T,class L> T& smin(T &x,L y){if(y<x)x=y;return x;}
typedef pair<int,int> pii;
const int maxn=2e5+17;
unordered_map<int,int>mp;
int numof(int x){
  int ans=0;
  while(x)
    ans++,x/=10;
  return ans;
}
int nxt(int x){
  int ans[17],p=0;
  while(x)
    ans[p++]=(x%10)-(x<0?-1:1),x/=10;
  int res=0;
  while(p--)
    res*=10,res+=ans[p];
  return res;
}
int prv(int x){
  int c=0,cx=x;
  while(x)
    c*=10,c+=(x<0?-1:1),x/=10;
  c*=10,c++;
  return cx-c;
}
int lst(int x){
  while(x>=10)
    x/=10;
  return x;
}
int del(int x){
  int ans[17],p=0;
  while(x>=10)
    ans[p++]=(x%10),x/=10;
  int res=0;
  while(p--)
    res*=10,res+=ans[p];
  return res;
}
int f(int x){
  if(x<=11)return min(13-x,x);
  if(mp[x])return mp[x];
  int n=0,t=1;
  while(t<x)
    t*=10,t++,n++;
  if(x*2>=t)
    return mp[x]=min(f(t-x)+n+1,(x/(t/10))*n+f(x%(t/10)));
  return mp[x]=(x/(t/10))*n+f(x%(t/10));
}
main(){
  //ios::sync_with_stdio(0),cin.tie(0);
  int a;
  cin>>a;
  //cerr<<numof(a)<<' '<<lst(a)<<' '<<del(a)<<'\n';
  cout<<f(a)<<'\n';
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const ll oo = 1000 * 1000 * 1000;

ll n, a[18];
ll ans = oo;

ll f(ll n, ll ind);

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

	cin >> n;

	a[0] = 1;
	for (int i = 1; i < 18; i++)
		a[i] = a[i - 1] * 10 + 1;

	cout << f(n, 17) << endl;

	return 0;
}

ll f(ll m, ll ind) {
	//cerr << m << endl;
	ll tmp = (m / a[ind]) * (ind + 1);
	m %= a[ind];
	if (m == 0)
		return tmp;
	return (tmp + min( ind + 1 + f(a[ind] - m, ind - 1), f(m, ind - 1)));
}


#include <bits/stdc++.h>
using namespace std;
long long nrs[16];
int solve(long long k, int i, int bm){
//	cout << k << ' ' << i << ' ' << bm << '\n';
	if(k==0)
		return 0;
	long long l = k;
	l = (l%nrs[i]+nrs[i])%nrs[i];
	if(bm%2)
		l-=nrs[i];
	long long cost = (abs(k-l)/nrs[i])*(i+1);
	return cost + solve(l,i-1,bm/2);
}
int main(){
	long long n;
	cin >> n;
	nrs[0]=1;
	for(int i = 1; i < 16; ++i)
		nrs[i]=nrs[i-1]*10+1;
	long long ans = n;
	for(int bm = 0; bm < (1<<15); ++bm){
		ans=min(ans,(long long)solve(n,15,bm));
	}
	cout << ans << '\n';
};


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
long long INF = 1e18;
long long ans = 0;
vector<int> dpr;
int solve(long long n){
	if (n==0) return 0;
	if (n<dpr.size() && dpr[n]) return dpr[n];
	long long lastdif = INF;
	long long x = 1;
	int i=0;
	while (abs(x-n)<=lastdif){
		lastdif = abs(x-n);
		x=x*10+1;
		i++;
	}
	x/=10;
	if (x>n && x/10) {
		if (n<dpr.size())return dpr[n]=min(i+solve(abs(x-n)),i-1+solve(abs(x/10-n)));
		return min(i+solve(abs(x-n)),i-1+solve(abs(x/10-n)));
	}
	if (n<dpr.size())
	return dpr[n]= i+solve(abs(x-n));
	return i+solve(abs(x-n));
}
int main(){
#ifdef NEKROLM
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
#endif
	ios_base::sync_with_stdio(false);
	long long n; cin >> n;
	dpr.resize(1e7);
	cout << solve(n);

	return 0;
}


#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
LL ones[17];
int solve(LL n,int i){
  int t = i*(n/ones[i]);
  n%=ones[i];
  if(n==0) return t;
  return t + min(i+solve(ones[i]-n,i-1),solve(n,i-1));
}
int main(){
  ones[0] = 0;
  for(int i=1;i<17;++i) ones[i] = ones[i-1]*10+1;
  LL n;
  cin >> n;
  cout << solve(n,16) << endl;
  return 0;
}


#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
long long num11[20];
long long pow10[20];
int ans = 0;
void pre()
{
    pow10[0] = 1;
    for (int i = 1; i <= 17; i++)
    {
        pow10[i] = pow10[i - 1] * 10;
    }
    for (int i = 1; i <= 17; i++)
    {
        num11[i] = num11[i - 1] * 10 + 1;
        // cout << i << ' ' << num11[i] << '\n';
    }
}
int get_len(long long x)
{
    int res = 0;
    while (x)
    {
        res++;
        x /= 10;
    }
    return res;
}
void dfs(int pos, long long x, int cnt)
{

    if (ans != -1 && cnt >= ans)    return;
    if (x == 0 || pos == 0)
    {
        if (ans != -1)  ans = min(ans, cnt);
        else    ans = cnt;
        return;
    }
    if (x < 0)  x = -x;
    // printf("pos = %d, x = %lld, cnt = %d， pow10[pos] = %lld\n", pos, x, cnt, pow10[pos - 1]);
    long long t_x = x;
    int t_cnt = 0;
    while (t_x >= pow10[pos - 1])
    {
        t_x -= num11[pos];
        t_cnt += pos;
    }
    dfs(pos - 1, t_x, cnt + t_cnt);
    t_x = num11[pos + 1] - x;    t_cnt = 0;
    while (t_x >= pow10[pos - 1])
    {
        t_x -= num11[pos];
        t_cnt += pos;
    }
    dfs(pos - 1, t_x, cnt + pos + 1 + t_cnt);
}

void Solve()
{

    long long x;    scanf("%lld", &x);
    // while (cin >> x)    cout << get_len(x);
    ans = -1;
    dfs(get_len(x), x, 0);
    cout << ans << '\n';
}
int main()
{
    pre();
    // while (1)
    Solve();
    getchar(); getchar();
    return 0;
}


#include<iostream>
#include<vector>
#include<algorithm>
#include<set>

using namespace std;

#define int long long

int st[1000000+5];

int a[1000000+5];

int b[1000000+5];

int c[1000000+5];

int fans=1e18;

void check()
{
    for (int i=0; i<18; i++)
    {
        a[i]=c[i];
    }
    for (int i=0; i<17; i++)
    {
        if (b[i]>0)
        {
            a[i+1]++;
            a[i]-=10;
            a[0]--;
        }
    }
    if (a[0]<-6)
    {
        a[0]+=11;
        a[1]--;
    }
    if (a[0]>6)
    {
        a[0]-=11;
        a[1]++;
    }
    int ans=0;
    for (int i=0; i<18; i++)
    {
        ans+=abs(a[i])*(i+1);
    }
    fans=min(fans,ans);
}

void pereb(int step)
{
    if (step>=17)
    {
        check();
        return;
    }
    for (int i=0; i<2; i++)
    {
        b[step]=i;
        pereb(step+1);
    }
}

int32_t main()
{
    int n;
    cin>>n;
    st[0]=1;
    for (int i=1; i<18; i++)
    {
        st[i]=st[i-1]*10+1;
    }
    int cur=n;
    int pos=17;
    while (cur>0)
    {
        c[pos]=cur/st[pos];
        cur%=st[pos];
        pos--;
    }
    pereb(0);
    cout<<fans;
}


#include <cstdio>
#include <cstring>
#include<iostream>
#include <algorithm>
using namespace std;
#define llu long long int
llu a[16] ;
llu f(llu n,llu i)
{
    llu num = n/a[i] ;
    //cout<<n<<" "<<i<<endl;
    n %= a[i] ;
    if(n == 0)  return num*i ;
    else  return num*i + min(i+f(a[i]-n,i-1),f(n,i-1) );
}
int main()
{
    llu n,i ;
    a[0]=0 ;
    for(i=1;i<=16;i++)  a[i]=a[i-1]*10 + 1 ;
    scanf("%lld",&n);
    printf("%lld\n",f(n,16));
	return 0;
}


#include <iostream>
#include <fstream>
#include <algorithm>
#include <unordered_map>

using namespace std;

typedef long long LL;

LL puteri[20];

int solve( LL number, int pos )
{
   LL contor = number / puteri[pos];

   if ( number % puteri[pos] == 0 )
            return pos * contor;

   int a = pos * contor + solve( number % puteri[pos], pos - 1 );
   int b = pos * ( contor + 1 ) + solve( puteri[pos] - ( number % puteri[pos] ), pos - 1 );

   return min( a, b );
}

int main()
{
    puteri[1] = 1;

    for ( int i = 2; i <= 17; ++i )
    {
        puteri[i] = puteri[i - 1] * 10LL + 1;
    }

    LL n;

    cin >> n;
    cout << solve( n, 17 );

    return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
#define reg register
#define ll long long

ll n;
ll ans;

ll ele[18];

int dfs(ll x)
{
	int res, now = 16;
	if (x <= 11) return min(x, 11 - x + 2);
	while(ele[now-1] >= x) now--;
	res = (x / ele[now-1]) * (now - 1) + dfs(x % ele[now-1]);
	if (x < ele[now] - x) return res;
	return min(res, now + dfs(ele[now] - x));
}

int main()
{
	ele[1] = 1;
	for (reg int i = 2 ; i <= 16 ; i ++) ele[i] = ele[i-1] * 10 + 1;
	scanf("%lld", &n);
	printf("%d\n", dfs(n));
	return 0;
}


#include<cstdio>
#include<iostream>
using namespace std;
long long n,f[18];
int Solve(long long x)
{
	int res,digits=15;
	if(x<=11ll) return min(x,13-x);
	while(f[digits]>=x) --digits;
	res=((x/f[digits])*digits)+Solve(x%f[digits]);
	if((x<<1ll)<f[digits+1]) return res;
	return min(res,digits+Solve(f[digits+1]-x)+1);
}
int main()
{
	f[1]=1;
	for(register int i=2;i<=16;++i) f[i]=f[i-1]*10+1;
	scanf("%lld",&n);
	printf("%d",Solve(n));
	return 0;
}


#include<bits/stdc++.h>
#define FOR(i,a,n) for(int i=a;i<n;i++)
#define si(x) scanf("%d",&x)
#define sll(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define pi(x) printf("%d\n",x)
#define pll(x) printf("%lld\n",x)
#define ps(x) printf("%s\n",ch)
#define M 1000000007
#define ll long long
#define mp make_pair
#define pb push_back
#define fr first
#define se second
using namespace std;
int c=0;
map<ll,ll> memo;
ll rec(ll n)
{
   // cout<<n<<endl;
    if(memo[n])
        return memo[n];
    if(n<=11)
    {
        return min(n,2+(11-n));
    }
    ll x=1,c=1;
    while(n>x)
        x=x*10+1,c++;
    if(x>n*2)
        return (n/(x/10))*(c-1)+rec(n%(x/10));
    return memo[n]=min(rec(x-n)+c,(n/(x/10))*(c-1)+rec(n%(x/10)));
}
int main()
{
    ll s;
    cin>>s;
    cout<<rec(s);
    return 0;
}


#include <cstdio>
#include <iostream>
using namespace std;
long long int xrr[18];
int res=0;

void dfs(int ans,long long int rem,int p)
{
	//cout<<"ans: "<<ans<<" rem: "<<rem<<endl;
	if(ans>res)
		return;
	if(rem==0)
	{
		res=min(ans,res);
		return;
	}
	int need = rem/xrr[p];
	dfs(ans+(p*need++),rem-(need*xrr[p]),p-1);
	dfs(p*need+ans,need*xrr[p]-rem,p-1);
}

int main()
{
	long long int x;
	cin>>x;
	xrr[1]=1;
	for(int i=2;i<18;i++)
		xrr[i]=(10*xrr[i-1])+1;
	long long int xp=x;
	while(xp>0)
	{
		for(int i=1;i<18;i++)
			if(xrr[i]>xp)
			{
				//cout<<xrr[i-1]<<endl;
				res+=(i-1);
				xp-=xrr[i-1];
				break;
			}
	}
	//cout<<"init: "<<res<<endl;
	dfs(0,x,16);
	cout<<res<<endl;;
}


#include <iostream>
#include <cstdio>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <iterator>

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define x0 abc
#define y0 ABC
#define x1 abcd
#define y1 ABCD
#define xn abcde
#define yn ABCDE

#define l_b lower_bound
#define u_b upper_bound

#define in insert
#define er erase

#define fi first
#define se second
#define m_p make_pair

#define p_b push_back
#define po_b pop_back

#define uns unsigned

#define ld long double
#define ll long long

#define cont continue
#define re return

#define MAXLL 9000000000000000000LL
#define MAXINT 2000000000

#define MINLL -9000000000000000000LL
#define MININT -2000000000

#define pi acos(-1.)

#define endl '\n'

#define OUT cout << "-------" << endl;

using namespace std;

using namespace __gnu_pbds;

typedef tree <int, null_type, less <int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

ll f[181], n, i, ans;

    ll Abs(ll a)
    {
        re (a < 0 ? -a : a);
    }

    void rec(ll nom, ll k)
    {
        ll i;

        if (n == 0) {
            ans = min(ans, k);

            re;
        }

        if (nom == 0)
        re;

        for (i = -10; i <= 10; i++)
            if (n + i * f[nom] > 0) {
                n += i * f[nom];

                rec(nom - 1, k + Abs(i) * nom);

                n -= i * f[nom];

                break;
            }

        for (i = -10; i <= 10; i++)
            if (n + i * f[nom] == 0) {
                n += i * f[nom];

                rec(nom - 1, k + Abs(i) * nom);

                n -= i * f[nom];

                break;
            }

        for (i = 10; i >= -10; i--)
            if (n + i * f[nom] < 0) {
                n += i * f[nom];

                rec(nom - 1, k + Abs(i) * nom);

                n -= i * f[nom];

                break;
            }
    }

int main()
{
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);

    ios::sync_with_stdio(0);
    cin.tie(0);

    cin >> n;

    f[1] = 1;

    for (i = 2; i <= 16; i++) f[i] = f[i - 1] * 10 + 1;

    ans = MAXLL;

    rec(16, 0);

    cout << ans << endl;

    re 0;
}


#include <iostream>
#include <map>
#include <cstdio>
using namespace std;

long long ones[20];

// Minimum number of ones that must be used if the largest sumand has at most
// i ones
int count_ones(long long n, int i){
	// Use as many i ones as possible
	int times = i * (n / ones[i]);
	n = n % ones[i];

	// If the number was complete
	if (n == 0) return times;

	// Decide whether to use one more of i ones to the substract or not
	return times +  min( i + count_ones(ones[i] - n, i-1), count_ones(n, i-1));
}

int main() {
	ones[0] = 0;
	for (int i = 1; i <= 16; ++i) ones[i] = ones[i-1] * 10 + 1;

	long long n;
	cin >> n;
	cout << count_ones(n, 16) << endl;

	return 0;
}


//ITNOG
#include<bits/stdc++.h>

using namespace std;
#define int long long

const int maxN = 100*1000 + 5;
//const int maxQ = 5000 + 5;
const int mod = 1000*1000*1000 + 7;
int dp[17];

int solve(int n, int t)
{
    if(t == 0)
    {
	  if(n == 0) return 0;
	  return mod;
    }

    int cnt = n / dp[t]; //cout << cnt << endl;
    if(n % dp[t] == 0) return t * cnt;
    return cnt * t + min(solve(abs(n - dp[t] * (cnt + 1)), t - 1) + t, solve(n - dp[t] * cnt, t - 1));
}
main()
{
    ios::sync_with_stdio(0); cin.tie(0);
    dp[1] = 1;
    for(int i = 2; i < 17; i ++)
	  dp[i] = dp[i - 1] * 10 + 1;

    int n; cin >> n;
//    cout << solve(n, 2) << endl;
    cout << solve(n, 16) << endl;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
long long n,b[20];
long long dfs(long long x,long long sum)
{
	long long num=x/b[sum];
	x=x%b[sum];
	if(x==0)
		return num*sum;
	else
		return num*sum+min(dfs(x,sum-1),sum+dfs(b[sum]-x,sum-1));
}
int main()
{
	cin >> n;
	for(int i=1;i<=17;i++)
		b[i]=b[i-1]*10ll+1ll;
	long long m=0,x=n;
	while(x!=0)
	{
		x/=10ll;
		m++;
	}
	cout << dfs(n,m+2) << endl;
	return 0;
}


#include <iostream>
#include <cstdio>
#define LL long long
using namespace std;
//tim so chu so cua n
int num(LL n){
   int num = 0;
    while(n){
        n /= 10;
        num++;
    }
    return num;
}
//tinh so co dang 11...1 lon nhat nhung khong vuot qua n
LL find(LL n){
    int ex = num(n);
    LL cur = 0, ad = 1;
    for(int i = 0; i <= ex-1; i++){
            cur += ad;
            ad *= 10;
    }
    if(cur <= n) return cur;
    return ((cur-1)/10);
}

LL process(LL n){
    if(n <= 6) return n;
    if(n <= 11) return (13 - n);
    LL less = find(n);
    LL more = less*10+1;
    if(n % less == 0){
        if(n <= more/2 + less) return num(less)*n / less;
        return num(more) + process(more - n);
    }
    else{
        LL _m = (n / less)*less;
        LL res = process(_m) + process(n - _m);
        if(n > more/2) res = min(process(_m) + process(n - _m), num(more) + process(more-n));
        return res;
    }
}
int main(){
    LL n;
    cin>>n;
    cout<<process(n)<<endl;
    return 0;
}


#include <iostream>
using namespace std;

#define F cin
#define G cout

long long n,a[16];

long long solve(long long n,int step)
{
    long long ans = (step+1LL)*(n/a[step]);
    n %= a[step];
    if ( n == 0 ) return ans;
    return ans + min(solve(n, step-1), step+1 + solve(a[step]-n, step-1));
}

int main()
{
    a[0] = 1;
    for (int i=1;i<16;++i)
        a[i] = a[i-1]*10 + 1;
    F>>n;
    G<<solve(n,15);
}


#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int gi(){
	int x=0,w=1;char ch=getchar();
	while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
	if(ch=='-')w=0,ch=getchar();
	while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
	return w?x:-x;
}
const int N=255;
const int mod=1e9+7;
int n,m,a[N],len,coef[N],dp[N];long long k;
void Inc(int &x,int y){x+=y;x>=mod?x-=mod:x;}
struct poly{
	int s[N];
	poly(){memset(s,0,sizeof(s));}
	void print(){
		for(int i=0;i<len;++i)printf("%d ",s[i]);
		puts("");
	}
};
poly operator + (poly a,poly b){
	for(int i=0;i<len;++i)Inc(a.s[i],b.s[i]);
	return a;
}
poly operator * (poly a,poly b){
	static int tmp[N<<1];
	for(int i=0;i<len;++i)
		for(int j=0;j<len;++j)
			Inc(tmp[i+j],1ll*a.s[i]*b.s[j]%mod);
	for(int i=len+len;i>=len;--i)
		if(tmp[i]){
			for(int j=1;j<=len;++j)Inc(tmp[i-j],1ll*coef[j]*tmp[i]%mod);
			tmp[i]=0;
		}
	for(int i=0;i<len;++i)a.s[i]=tmp[i],tmp[i]=0;
	return a;
}
poly fastpow(poly x,long long y){
	poly res;res.s[0]=1;
	while(y){if(y&1)res=res*x;x=x*x;y>>=1;}
	return res;
}
int main(){
	scanf("%d%d%lld",&n,&m,&k);
	for(int i=1;i<=n;++i)scanf("%d",&a[i]);
	for(int i=1,x;i<=m;++i)scanf("%d",&x),++coef[x],len=max(len,x);
	poly S,T;len==1?T.s[0]=coef[1]:T.s[1]=1;
	for(int i=1;i<=n;++i)S=S+fastpow(T,a[i]);
	S=fastpow(S,k);
	for(int i=dp[0]=1;i<len;++i)
		for(int j=1;j<=i;++j)
			Inc(dp[i],1ll*coef[j]*dp[i-j]%mod);
	int ans=0;
	for(int i=0;i<len;++i)Inc(ans,1ll*dp[i]*S.s[i]%mod);
	printf("%d\n",ans);return 0;
}


#define _CRT_SECURE_NO_DEPRECATE
#include <algorithm>
#include <string>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <iostream>
#include <iterator>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <ctime>
#include <cstring>
#pragma comment(linker, "/STACK:16777216")
using namespace std;
#define pb push_back
#define ppb pop_back
#define pi 3.1415926535897932384626433832795028841971
#define mp make_pair
#define x first
#define y second
#define pii pair<int,int>
#define pdd pair<double,double>
#define INF 1000000000
#define FOR(i,a,b) for (int _n(b), i(a); i <= _n; i++)
#define FORD(i,a,b) for(int i=(a),_b=(b);i>=_b;i--)
#define all(c) (c).begin(), (c).end()
#define SORT(c) sort(all(c))
#define rep(i,n) FOR(i,1,(n))
#define rept(i,n) FOR(i,0,(n)-1)
#define L(s) (int)((s).size())
#define C(a) memset((a),0,sizeof(a))
#define VI vector <int>
#define ll long long

struct post {
	int pos[3];
	int st[3];
	int mv;
};
inline int code(const post& p) {
	int q = p.mv;
	rept(i,3) q = q * 44 + p.pos[i];
	rept(i,3) q = q * 5 + p.st[i];
	return q;
}
inline post decode(int q) {
	post p;
	FORD(i,2,0) {
		p.st[i] = q % 5;
		q /= 5;
	}
	FORD(i,2,0) {
		p.pos[i] = q % 44;
		q /= 44;
	}
	p.mv = q;
	return p;
}
int a,b,c,d,i,j,n,m,k;
int ans = 0;
bool used[100000001];
int fm[3],ft[3];
queue<int> q;

inline void add(const post &p) {
	rept(i,3) {
		if (p.pos[i] < 0) return;
		if (p.pos[i] > ans) ans = p.pos[i];
	}
	int qq = code(p);
	if (used[qq]) return;
	used[qq] = 1;
	q.push(qq);
}
int main()
{
	//freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);

	post p;
	C(p.pos); C(p.st); p.mv = 0;
	rept(i,3) {
		scanf("%d%d%d",&p.pos[i], &fm[i], &ft[i]);
		p.pos[i]+=2;
	}
	add(p);
	while (!q.empty()) {
		post cur = decode(q.front());
		/*if (cur.pos[0] == 6 + 1 && cur.pos[1] == 4 + 1 && cur.pos[2] == 5 + 1 && cur.mv==5 && cur.st[2] = 1 + 1) {
			a = a;
		}*/
		q.pop();
		// move
		rept(i,3) {
			if (cur.mv & 1 << i) continue;
			if (cur.st[i] !=0 && cur.st[i] !=4) continue;
			bool ok = 1;
			rept(j,3) {
				if (cur.st[j] == i + 1) {
					ok = 0;
					break;
				}
			}
			if (!ok) continue;
			FOR(dx, -fm[i], fm[i]) {
				if (!dx) continue;
				post nx = cur;
				nx.pos[i] += dx;
				int o = 0;
				rept(z,3) {
					if (nx.pos[z] == nx.pos[i]) ++o;
				}
				if (o > 1) continue;
				nx.mv |= 1 << i;
				add(nx);
			}
		}

		// lift
		rept(i,3) {
			if (cur.st[i] != 0) continue;
			bool ok = 1;
			rept(j,3) {
				if (cur.st[j] == i + 1) {
					ok = 0;
					break;
				}
			}
			if (!ok) continue;
			rept(j,3) {
				if (i == j) continue;
				if (cur.pos[j] != cur.pos[i] + 1 && cur.pos[j] != cur.pos[i] - 1) continue;
				bool ok = 1;
				rept(z, 3) {
					if (cur.st[z] == j + 1) {
						ok = 0;
						break;
					}
				}
				if (!ok) continue;
				post nx = cur;
				nx.st[i] = j + 1;
				nx.pos[j] = nx.pos[i];
				if (nx.st[j] != 0 && nx.st[j] != 4) {
					rept(z,3) nx.pos[z] = cur.pos[i];
				}
				add(nx);
			}
		}

		// throw
		rept(i,3) {
			if (cur.st[i] == 0 || cur.st[i] == 4) continue;
			bool ok = 1;
			rept(j,3) {
				if (cur.st[j] == i + 1) {
					ok = 0;
					break;
				}
			}
			if (!ok) continue;

			FOR(dx, -ft[i], ft[i]) {
				if (!dx) continue;
				bool ok = 1;
				rept(z, 3) {
					if (cur.pos[z] == dx + cur.pos[i]) continue;
				}
				post nx = cur;
				int pt = cur.st[i] - 1;
				nx.pos[pt] = cur.pos[i] + dx;
				if (cur.st[pt] > 0 && cur.st[pt] < 4) nx.pos[cur.st[pt] - 1] = cur.pos[i] + dx;
				nx.st[i] = 4;
				add(nx);
			}
		}
	}

	printf("%d\n", ans - 2);
}


#include <bits/stdc++.h>
using namespace std;
#define mz 1000000007

int l;
struct Mat
{
    long long v[45][45]={};
    Mat friend operator *(Mat x1,Mat x2)
    {
        Mat x3;
        for(int i=0;i<l;i++)
            for(int k=0;k<l;k++)
                for(int j=0;j<l;j++)
                    x3.v[i][j]+=x1.v[i][k]*x2.v[k][j];
        return x3;
    }
};
char s[105];

bool ok(int l1,int l2)
{
    if(l1)
    {
        if(s[l1]==s[l2+1])
            return 0;
        for(int i=l1-1,j=l2;i>0;i--,j--)
        {
            if(s[i]!=s[j])
                return 0;
        }
    }
    return 1;
}
Mat pows(Mat x,int y)
{
    Mat ans;
    for(int i=0;i<l;i++)
        ans.v[i][i]=1;
    while(y)
    {
        if(y%2)
            ans=x*ans;
        x=x*x;
        y>>=1;
    }
    return ans;
}

int main()
{
    int n;
    long long ans;
    Mat a;
    scanf("%d",&n);
    scanf("%s",s+1);
    l=strlen(s+1);
    ans=1LL<<n;
    for(int i=0;i<l;i++)
    {
        if(i+1<l)
            a.v[i][i+1]=1;
        for(int j=i;j>=0;j--)
        {
            if(ok(j,i))
            {
                a.v[i][j]=1;
                break;
            }
        }
    }
    a=pows(a,n);
    for(int i=0;i<l;i++)
        ans-=a.v[i][i];
    printf("%lld\n",ans);
    return 0;
}


#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#define rep(i,x,y) for(int i=(x);i<=(y);i++)
#define dep(i,x,y) for(int i=(x);i>=(y);i--)
#define gc getchar()
#define pb push_back
#define N 1000000
using namespace std;
int n,m,q,nn,mm,al,u,R,x,y,ff[N][19];
int p[N],ex[N],ey[N],Ex[N],Ey[N],f[N],F[N],ro[N];
int TT[N],h[N],H[N],v[N],g[N],G[N],te[N],dfn[N],nd[N],uz[N];
vector<int>e[N],w[N];
bool cmp(const int &x,const int &y){return dfn[x]<dfn[y];}
int gf(int x){if(g[x]==x)return x;g[x]=gf(g[x]);return g[x];}
int Gf(int x){if(G[x]==x)return x;G[x]=Gf(G[x]);return G[x];}
int Tr(int x){if(te[x]==x)return x;te[x]=Tr(te[x]);return te[x];}
void dfs(int x){int sz=e[x].size()-1;
	dfn[x]=al++;ff[x][0]=f[x];v[x]=1;
	rep(i,1,18)ff[x][i]=ff[ff[x][i-1]][i-1];
	rep(i,0,sz){int tt=e[x][i];
		if(!v[tt]){ro[tt]=ro[x];h[tt]=h[x]+1;f[tt]=x;dfs(tt);}
	}
}
int lca(int x,int y){
	if(h[x]<h[y])swap(x,y);
	dep(i,18,0)if((h[x]-(1<<i))>=h[y])x=ff[x][i];
	dep(i,18,0)if(ff[x][i]!=ff[y][i])x=ff[x][i],y=ff[y][i];
	if(x!=y)x=f[x],y=f[y];return g[x];
}
void DFS(int x){
	int sz=w[x].size()-1;v[x]=1;
	rep(i,0,sz){int tt=w[x][i];
		if(!v[tt]){F[tt]=x;H[tt]=H[x]+1;DFS(tt);}
	}
}
void read(int &x){char c=gc;x=0;
	while(c<'0'||c>'9')c=gc;
	for(;c>='0'&&c<='9';c=gc)x=x*10+c-'0';
	x=(x+R-1)%n+1;
}
int main(){
	scanf("%d%d%d",&n,&m,&q);
	rep(i,1,m){
		read(ex[i]);read(ey[i]);
		e[ex[i]].pb(ey[i]);e[ey[i]].pb(ex[i]);
	}al=0;
	rep(i,1,n)if(!v[i]){h[i]=1;ro[i]=i;f[i]=i;dfs(i);}
	rep(i,1,n)v[i]=0,g[i]=i;
	rep(i,1,m){
		if(f[ey[i]]==ex[i])swap(ex[i],ey[i]);
		if(v[ex[i]]||f[ex[i]]!=ey[i]){
			x=gf(ex[i]);y=gf(ey[i]);
			while(x!=y){
				if(h[x]>h[y]){g[gf(x)]=gf(f[x]);x=gf(x);}
				else{g[gf(y)]=gf(f[y]);y=gf(y);}
			}
		}else v[ex[i]]=1;
	}
	rep(i,1,n)gf(i);
	rep(o,1,q){
		scanf("%d%d",&nn,&mm);al=0;
		rep(i,1,nn){read(p[i]);p[i]=g[p[i]];nd[++al]=p[i];}
		rep(i,1,mm)uz[i]=0;
		rep(i,1,mm){
			read(Ex[i]);read(Ey[i]);
			Ex[i]=g[Ex[i]];Ey[i]=g[Ey[i]];
			nd[++al]=Ex[i];nd[++al]=Ey[i];
		}
		sort(nd+1,nd+al+1,cmp);
		al=unique(nd+1,nd+al+1)-(nd+1);u=al-1;
		rep(i,1,u)nd[++al]=lca(nd[i],nd[i+1]);
		sort(nd+1,nd+al+1,cmp);
		al=unique(nd+1,nd+al+1)-(nd+1);
		rep(i,1,al)TT[nd[i]]=i,te[i]=i;
		rep(i,2,al)if(ro[nd[i]]==ro[nd[i-1]])te[Tr(i)]=Tr(i-1);
		rep(i,1,al){F[i]=0;w[i].clear();}
		rep(i,2,al){
			if(Tr(i)!=Tr(i-1))continue;F[i]=i-1;
			while(lca(nd[i],nd[F[i]])!=nd[F[i]])F[i]=F[F[i]];
			w[i].pb(F[i]);w[F[i]].pb(i);
		}
		rep(i,1,mm){
			x=TT[Ex[i]];y=TT[Ey[i]];
			if(Tr(x)!=Tr(y)){
				w[x].pb(y);w[y].pb(x);
				te[Tr(x)]=Tr(y);uz[i]=1;
			}
		}
		rep(i,1,al)F[i]=0,v[i]=0,G[i]=i,H[i]=0;
		rep(i,1,al)if(!v[i]){H[i]=1;DFS(i);}
		rep(i,1,mm)if(!uz[i]){
			x=Gf(TT[Ex[i]]);y=Gf(TT[Ey[i]]);
			while(x!=y){
				if(H[x]>H[y]){G[Gf(x)]=Gf(F[x]);x=Gf(x);}
				else{G[Gf(y)]=Gf(F[y]);y=Gf(y);}
			}
		}
		u=0;rep(i,2,nn)if(Gf(TT[p[i]])!=Gf(TT[p[1]])){u=1;break;}
		if(u)printf("NO\n");else{printf("YES\n");R=(R+o-1)%n+1;}
	}
}


#include<bits/stdc++.h>
#define rep(i,a,b) for (int i=(a); i<=(b); i++)
#define per(i,a,b) for (int i=(a); i>=(b); i--)
using namespace std;
typedef long long ll;

const int maxn = 300005;
const int mod = 1000000007;
int f[30], n, m, k, len, A, B, AA, AB, BA;
char s[30][maxn], t[maxn];
ll K;

int tmp[2][2], res[2][2], bin[2][2];
void mul(int a[2][2], int b[2][2], int c[2][2]) {
	rep (i, 0, 1) rep (j, 0, 1) {
		tmp[i][j] = 0;
		rep (k, 0, 1) tmp[i][j] = (tmp[i][j] + 1ll * a[i][k] * b[k][j]) % mod;
	}
	rep (i, 0, 1) rep (j, 0, 1) c[i][j] = tmp[i][j];
}

void power(int a[2][2], ll p) {
	rep (i, 0, 1) rep (j, 0, 1)
		res[i][j] = (i == j), bin[i][j] = a[i][j];
	while (p) {
		if (p & 1) mul(res, bin, res);
		mul(bin, bin, bin); p >>= 1;
	}
	rep (i, 0, 1) rep (j, 0, 1)
		a[i][j] = res[i][j];
}

int MA[2][2], MB[2][2];
int getfib(ll k) {
	MB[0][0] = MB[1][0] = MB[0][1] = 1; MB[1][1] = 0;
	MA[0][0] = 1; MA[1][0] = 0;
	power(MB, k - 1);
	mul(MB, MA, MA);
	return MA[0][0];
}

int nxt[maxn];
int calc(char s[maxn], int ls, char t[maxn], int lt) {
	int k, res = 0;
	nxt[1] = k = 1; res = 0;
	//printf("%s\n", t + 1);
	rep (i, 2, ls) {
		while (k >= 2 && s[i] != s[k]) k = nxt[k-1];
		if (s[i] == s[k]) k++;
		nxt[i] = k;
		//printf("%d\n", nxt[i]);
	}
	k = 1;
	rep (i, 1, lt) {
		while (k >= 2 && t[i] != s[k]) k = nxt[k-1];
		if (t[i] == s[k]) k++;
		//printf("%d %d\n", i, k);
		if (k == ls + 1) res++, k = nxt[k-1];
	}
	return res;
}

int flag[maxn];
char revB[maxn], revt[maxn];
int solve(char A[maxn], int lA, char B[maxn], int lB, char t[maxn], int lt) {
	rep (i, 1, lt - 1) flag[i] = 0;
	rep (i, 1, lB) revB[i] = B[lB+1-i];
	rep (i, 1, lt) revt[i] = t[lt+1-i];
	int k; nxt[1] = k = 1;
	rep (i, 2, lt) {
		while (k >= 2 && t[i] != t[k]) k = nxt[k-1];
		if (t[i] == t[k]) k++;
		nxt[i] = k;
	}
	k = 1;
	rep (i, 1, lA) {
		while (k >= 2 && A[i] != t[k]) k = nxt[k-1];
		if (A[i] == t[k]) k++;
		if (k == lt + 1) k = nxt[k-1];
	}
	while (k >= 2) {
		flag[lt-(k-1)]++;
		k = nxt[k-1];
	}
	nxt[1] = k = 1;
	rep (i, 2, lt) {
		while (k >= 2 && revt[i] != revt[k]) k = nxt[k-1];
		if (revt[i] == revt[k]) k++;
		nxt[i] = k;
	}
	k = 1;
	rep (i, 1, lB) {
		while (k >= 2 && revB[i] != revt[k]) k = nxt[k-1];
		if (revB[i] == revt[k]) k++;
		if (k == lt + 1) k = nxt[k-1];
	}
	while (k >= 2) {
		flag[k-1]++;
		k = nxt[k-1];
	}
	int res = 0;
	rep (i, 1, lt - 1)
		if (flag[i] == 2) res++;
	return res;
}
/*
10 1
bb
*/
int main() {
	f[1] = f[m=2] = 1;
	while (f[m-1] < 100000) {
		f[m+1] = f[m] + f[m-1];
		m++;
	}
	s[1][1] = 'a'; s[2][1] = 'b';
	rep (i, 3, m) {
		rep (j, 1, f[i-1])
			s[i][j] = s[i-1][j];
		rep (j, 1, f[i-2])
			s[i][j+f[i-1]] = s[i-2][j];
	}
	cin >> K >> n;
	while (n--) {
		scanf("%s", t + 1);
		len = strlen(t + 1); k = 1;
		while (f[k] < len) k++;
		if (K < k) { puts("0"); continue; }
		if (K == k) { printf("%d\n", calc(t, len, s[k], f[k])); continue; }
		if (K == k + 1) { printf("%d\n", calc(t, len, s[k+1], f[k+1])); continue; }
		A = calc(t, len, s[k+1], f[k+1]);
		B = calc(t, len, s[k], f[k]);
		AA = solve(s[k+1], f[k+1], s[k+1], f[k+1], t, len);
		AB = solve(s[k+1], f[k+1], s[k], f[k], t, len);
		BA = solve(s[k], f[k], s[k+1], f[k+1], t, len);
		int f0 = getfib(K - k), f1 = getfib(K - k - 1);		//f0 A    f1 B
		//printf("%d %d %d %d %d %d %d\n", A, B, AA, AB, BA, f0, f1);
		int ans = (1ll * f0 * A + 1ll * f1 * B) % mod;
		if ((K - k) & 1) {
			ans = (ans + 1ll * f1 * AB) % mod;
			ans = (ans + 1ll * f1 * BA) % mod;
			ans = (ans + 1ll * (f0 - f1 + mod - 1) * AA) % mod;
		}
		else {
			ans = (ans + 1ll * f1 * AB) % mod;
			ans = (ans + 1ll * (f1 + mod - 1) * BA) % mod;
			ans = (ans + 1ll * (f0 - f1 + mod) * AA) % mod;
		}
		printf("%d\n", ans);
	}
	return 0;
}


#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+5;

int read()
{
	int s=0;
	char c=getchar(),lc='+';
	while (c<'0'||'9'<c) lc=c,c=getchar();
	while ('0'<=c&&c<='9') s=s*10+c-'0',c=getchar();
	return lc=='-'?-s:s;
}
void write(int x)
{
	if (x<0)
	{
		putchar('-');
		x=-x;
	}
	if (x<10) putchar(x+'0');
	else
	{
		write(x/10);
		putchar(x%10+'0');
	}
}
void print(int x,char c='\n')
{
	write(x);
	putchar(c);
}
int sum[N],ans,p;
int power(int a,int b)
{
	int ret=1;
	while (b)
	{
		if (b&1) ret=ret*a%p;
		a=a*a%p;
		b/=2;
	}
	return ret;
}
int calc(int x,int y)
{
	int ret=0;
	for (int i=1;i<=x;i++) ret=(ret+sum[i+y]-sum[i]+p)%p;
//	print(x,',');print(y,':');print(ret);
	return ret;
}
int tot[N][2];
void Count(int l,int r,int h,int Min)
{
	if (r-l+1==Min) tot[h][0]++;
			   else tot[h][1]++;
	if (h==1) return void(ans=(ans+(r-l+1)*(r-l)%p*power(4,p-2)%p)%p);
	if (l==r) return;
	int mid=(l+r)/2;
	Count(l,mid,h-1,Min/2);
	Count(mid+1,r,h-1,Min/2);
}
void merge_sort(int h,int Min)
{
	if (h<=0) return;
	if (h==1) ans=(ans+tot[h][0]*(tot[h][0]-1)/2%p*calc(Min,Min)%p+tot[h][1]*(tot[h][1]-1)/2%p*calc(Min+1,Min+1)%p+tot[h][0]*tot[h][1]%p*calc(Min,Min+1)%p)%p;
	merge_sort(h-1,Min/2);
}

signed main()
{
	memset(tot,0,sizeof(tot));
	int n=read(),k=read();
    p=read();
	for (int i=1;i<=n*2;i++) sum[i]=(sum[i-1]+power(2,p-2)-power(i,p-2)+p)%p;
	Count(1,n,k,n);
	merge_sort(k,n);
//	for (int i=1;i<=k;i++) print(tot[i][0],' '),print(tot[i][1]);
	print(ans);

	return 0;
}