#include #ifdef LOCAL #include "./debug.cpp" #else #define debug(...) #define print_line #endif using namespace std; using ll = long long; int main() { int N, K; ll seed, a, b, m; cin >> N >> K >> seed >> a >> b >> m; vector F(2 * N + 1), W(N), V(N); F[0] = seed; for (int i = 0; i < 2 * N; i++) F[i + 1] = (a * F[i] + b) % m; for (int i = 0; i < N; i++) { W[i] = F[i] % 3 + 1; V[i] = W[i] * F[N + i]; } priority_queue PQ1, PQ2, PQ3; for (int i = 0; i < N; i++) { if (W[i] == 1) { PQ1.push(V[i]); } else if (W[i] == 2) { PQ2.push(V[i]); } else { PQ3.push(V[i]); } } while (!PQ1.empty()) { if (PQ1.size() >= 3) { ll a = PQ1.top(); PQ1.pop(); ll b = PQ1.top(); PQ1.pop(); ll c = PQ1.top(); PQ1.pop(); if (!PQ2.empty()) { ll d = PQ2.top(); PQ2.pop(); if (b + c > d) { PQ3.push(a + b + c); PQ2.push(d); } else { PQ3.push(a + d); PQ1.push(b); PQ1.push(c); } } } else if (PQ1.size() == 2) { ll a = PQ1.top(); PQ1.pop(); ll b = PQ1.top(); PQ1.pop(); if (!PQ2.empty()) { ll d = PQ2.top(); PQ2.pop(); if (a + b > d) { PQ2.push(a + b); PQ2.push(d); } else { break; } } } } while (!PQ2.empty()) { ll b = PQ2.top(); PQ2.pop(); if (!PQ1.empty()) { ll a = PQ1.top(); PQ1.pop(); PQ3.push(a + b); } else { PQ3.push(b); } } while (!PQ1.empty()) { ll a = PQ1.top(); PQ1.pop(); PQ3.push(a); } ll ans = 0; while (K-- && !PQ3.empty()) { ans += PQ3.top(); PQ3.pop(); } cout << ans << endl; }