/* -*- coding: utf-8 -*- * * 2617.cc: No.2617 螳ケ驥・縺ョ繝翫ャ繝励じ繝・け - yukicoder */ #include #include #include using namespace std; /* constant */ const int MAX_N = 1000000; /* typedef */ using ll = long long; using vl = vector; /* global variables */ int fs[MAX_N * 2]; vl wvs[4], wvss[4]; /* subroutines */ /* main */ int main() { int n, k, seed, a, b, m; scanf("%d%d%d%d%d%d", &n, &k, &seed, &a, &b, &m); for (int i = 0, f = seed; i < n * 2; i++) { fs[i] = f; f = ((ll)a * f + b) % m; } for (int i = 0; i < n; i++) { int w = fs[i] % 3 + 1; ll v = (ll)fs[n + i] * w; //printf(" %d,%lld", w, v); wvs[w].push_back(v); } //putchar('\n'); for (int w = 1; w <= 3; w++) { sort(wvs[w].begin(), wvs[w].end(), greater()); int l = wvs[w].size(); wvss[w].assign(l + 1, 0); for (int i = 0; i < l; i++) wvss[w][i + 1] = wvss[w][i] + wvs[w][i]; } auto &wvs3 = wvss[3], &wvs2 = wvss[2], &wvs1 = wvss[1]; int l3 = wvs[3].size(), l2 = wvs[2].size(), l1 = wvs[1].size(); ll maxsum = 0; int maxi = min(k, l3); for (int i3 = 0; i3 <= maxi; i3++) { int l21 = k - i3; int i2 = 0, j2 = min(l2, l21); while (i2 + 2 < j2) { int ii2 = (i2 * 2 + j2) / 3; int jj2 = (i2 + j2 * 2) / 3; ll si = wvs2[ii2] + wvs1[min(ii2 + (l21 - ii2) * 3, l1)]; ll sj = wvs2[jj2] + wvs1[min(jj2 + (l21 - jj2) * 3, l1)]; if (si < sj) i2 = ii2; else j2 = jj2; } for (int i = i2; i <= j2; i++) { ll sum = wvs3[i3] + wvs2[i] + wvs1[min(i + (l21 - i) * 3, l1)]; maxsum = max(maxsum, sum); } } printf("%lld\n", maxsum); return 0; }