/* -*- 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]; /* 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()); ll sum = 0; int j1 = wvs[1].size() - 1; int j2 = wvs[2].size() - 1; int j3 = wvs[3].size() - 1; for (int i = 0; i < k; i++) { ll maxv = 0; int op = -1; if (j3 >= 0 && maxv < wvs[3][j3]) maxv = wvs[3][j3], op = 0; if (j2 >= 0 && j1 >= 0 && maxv < wvs[2][j2] + wvs[1][j1]) maxv = wvs[2][j2] + wvs[1][j1], op = 1; if (j1 >= 2 && maxv < wvs[1][j1] + wvs[1][j1 - 1] + wvs[1][j1 - 2]) maxv = wvs[1][j1] + wvs[1][j1 - 1] + wvs[1][j1 - 2], op = 2; if (j2 >= 0 && maxv < wvs[2][j2]) maxv = wvs[2][j2], op = 3; if (j1 >= 1 && maxv < wvs[1][j1] + wvs[1][j1 - 1]) maxv = wvs[1][j1] + wvs[1][j1 - 1], op = 4; if (j1 >= 0 && maxv < wvs[1][j1]) maxv = wvs[1][j1], op = 5; if (op < 0) break; sum += maxv; switch (op) { case 0: j3--; break; case 1: j2--, j1--; break; case 2: j1 -= 3; break; case 3: j2--; break; case 4: j1 -= 2; break; case 5: j1--; break; } } printf("%lld\n", sum); return 0; }