import std.conv, std.functional, std.range, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } string COLOR(string s = "") { return "\x1b[" ~ s ~ "m"; } bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } } bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } } int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; } int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); } int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); } enum INF = 10L^^18; void main() { try { for (; ; ) { const N = readInt; const K = readInt; auto W = new long[N + 1]; auto V = new long[N + 1]; { const Seed = readLong; const A = readLong; const B = readLong; const M = readLong; auto F = new long[2 * N + 1]; F[1] = Seed; foreach (i; 1 .. 2 * N) { F[i + 1] = (A * F[i] + B) % M; } foreach (i; 1 .. N + 1) { W[i] = F[i] % 3 + 1; V[i] = W[i] * F[N + i]; } } debug { writeln("W = ", W); writeln("V = ", V); } auto vss = new long[][4]; foreach (i; 1 .. N + 1) { vss[W[i]] ~= V[i]; } foreach_reverse (w; 1 .. 3 + 1) { vss[w].sort!"a > b"; debug { writeln(w, ": ", vss[w]); } } int[4] lens; auto vsSums = new long[][4]; foreach (w; 1 .. 3 + 1) { lens[w] = cast(int)(vss[w].length); vsSums[w] = new long[lens[w] + 1]; foreach (i; 0 .. lens[w]) { vsSums[w][i + 1] = vsSums[w][i] + vss[w][i]; } } long ans; foreach (k; 0 .. K + 1) { long get3(int i) { if (i >= lens[3]) return -INF; return vss[3][i]; } long get1(int i) { if (k + 3 * i + 3 > lens[3]) return -INF; return (vsSums[1][k + 3 * i + 3] - vsSums[1][k + 3 * i]); } int lo = 0, hi = (K - k) + 1; for (; lo + 1 < hi; ) { const mid = (lo + hi) / 2; ((get3(mid - 1) > get1((K - k) - mid)) ? lo : hi) = mid; } foreach (i; lo - 10 .. lo + 10) if (0 <= i && i <= K - k) { long score; score += vsSums[3][min(i, lens[3])]; score += vsSums[2][min(k, lens[2])]; score += vsSums[1][min(k + 3 * ((K - k) - i), lens[1])]; chmax(ans, score); } } writeln(ans); } } catch (EOFException e) { } }