#include #include #include #define int long long #define rep(i, n) for(i = 0; i < n; i++) using namespace std; int solve(vector w, vector v, int K) { int n = w.size(); int i, j; vector items[4]; //items[重さ] : 価値リスト(降順) vector ruiseki[4]; //ruiseki[重さ][i]: items[重さ][0~i-1]の総和 rep(i, n) items[w[i]].push_back(v[i]); for (i = 1; i <= 3; i++) { sort(items[i].begin(), items[i].end(), greater()); //実装を簡単にするため、アイテム数を3K, K, Kに合わせる if (i == 1) { while (items[i].size() < 3 * K) items[i].push_back(0); items[i].resize(3 * K); } else { while (items[i].size() < K) items[i].push_back(0); items[i].resize(K); } //累積和 ruiseki[i].resize(items[i].size() + 1); ruiseki[i][0] = 0; rep(j, items[i].size()) { ruiseki[i][j + 1] = ruiseki[i][j] + items[i][j]; } } int ans = 0; rep(i, K + 1) { //重さ3のitemの個数iを探索 //f(K - i, j) = ナップザックK - i個、重さ2のアイテムをj個使うときの最大価値 //としたとき、f(K - i, j + 1) - f(K - i, j) <= 0を満たす最小のj (0 <= j < K, 無ければj = K) は? int ng = -1, ok = K - i, mid; //(ng, ok] while (ok - ng >= 2) { mid = (ok + ng) / 2; //f(K - i, mid + 1) - f(K - i, mid) <= 0かどうか判定する int delta_f = items[2][mid] - items[1][3 * (K - i) - 2 * mid - 1] - items[1][3 * (K - i) - 2 * mid - 2]; if (delta_f <= 0) ok = mid; else ng = mid; } int res = ruiseki[2][ok] + ruiseki[1][3 * (K - i) - 2 * ok]; ans = max(ans, res + ruiseki[3][i]); } return ans; } signed main() { int N, K, seed, a, b, m; cin >> N >> K >> seed >> a >> b >> m; vector f(2 * N); f[0] = seed; for (int i = 1; i < 2 * N; i++) { f[i] = (a * f[i - 1] + b) % m; } vector w(N), v(N); for (int i = 0; i < N; i++) { w[i] = f[i] % 3 + 1; v[i] = w[i] * f[N + i]; } int ans = solve(w, v, K); cout << ans << endl; return 0; }