#include #include using mint = atcoder::modint998244353; //using mint = atcoder::modint1000000007; using namespace atcoder; using namespace std; using ll = long long; using pi = pair; using pl = pair; using vi = vector; using vm = vector; using vvi = vector; using vl = vector; using vvl = vector; using vpi = vector>; using vpl = vector>; #define rep(i,n) for (ll i = 0; i < n; i++) #define replr(i,l,r) for (ll i = l; i < r; i++) const int inf =1e9; const ll infl = 4e18; template bool chmax(T &a, const T& b) {if (a < b) {a = b; return true;}return false;} template bool chmin(T &a, const T& b) {if (a > b) {a = b; return true;}return false;} template T max(vector &v) {T m = 0;for (auto x : v) chmax(m, x);return m;} template T min(vector &v) {T m = inf;for (auto x : v) chmin(m, x);return m;} template void print(vector &v){for(auto x : v){cout<> N >> A >> B >> C; vl dp(2*N,infl); dp[2]=A; ll p=1; replr(i,2,N-1){ ll n=i; ll cost=B; while (cost*B<=N*A){ n*=i; if (n>=2*N){ n%=N; n+=N; } cost*=B; chmin(dp[n],dp[i]+cost); } p*=i; if (p>=2*N){ p%=N; p+=N; } chmin(dp[p],dp[i]+C); chmin(dp[i+1],dp[i]+A); } vl dist(N,infl); priority_queue,greater> pq; rep(i,N){ pq.push({dp[i+N],i}); } while (!pq.empty()){ auto [d,n]=pq.top(); pq.pop(); if (dist[n]<=d) continue; dist[n]=d; if (dist[(n+1)%N]>d+A){ pq.push({d+A,(n+1)%N}); } ll cost=B; ll nn=n; while (cost*B<=N*A){ nn*=n; nn%=N; cost*=B; if (dist[nn]>d+cost){ pq.push({d+cost,nn}); } } if (dist[0]>d+C){ pq.push({d+C,0}); } } cout << dist[0] << '\n'; }