#pragma GCC optimize("Ofast") #include using namespace std; typedef long long int ll; typedef unsigned long long int ull; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); ll myRand(ll B) { return (ull)rng() % B; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, k; cin >> n >> k; ll seed, a, b, m; cin >> seed >> a >> b >> m; vector f(2 * n); f[0] = seed; for (int i = 1; i < 2 * n; i++) { f[i] = (f[i - 1] * a + b) % m; } vector v[3]; for (int i = 0; i < n; i++) { int w = f[i] % 3 + 1; v[w - 1].push_back(w * f[n + i]); } for (int i = 0; i < 3; i++) { sort(v[i].rbegin(), v[i].rend()); } vector dp(n + 1); int o = 0, t = 0; for (int i = 1; i <= n; i++) { ll p = 0, b = 0; if (o < v[0].size()) p += v[0][o]; if (o + 1 < v[0].size()) p += v[0][o + 1]; if (o + 2 < v[0].size()) p += v[0][o + 2]; if (t < v[1].size()) b += v[1][t]; if (o < v[0].size()) b += v[0][o]; if (p <= b) { dp[i] = dp[i - 1] + b; t += 1, o += 1; } else { dp[i] = dp[i - 1] + p; o += 3; } } ll res = 0; ll sum = 0; for (int i = 0; i <= v[2].size(); i++) { if (i > k) break; res = max(res, sum + dp[k - i]); if (i == v[2].size()) break; sum += v[2][i]; } cout << res << endl; }