voidsolve(int n, vector<int>& values, vector<int>& colors, int a, int b){ // define dp[c]: the max value we can get when ending with color c vector<longlong> dp(n + 1, LLONG_MIN); longlong mx1 = 0, mx2 = 0; int mc = -1; for (int i = 0; i < n; i++) { longlong v = values[i]; int c = colors[i]; /* how to get the maxValue ending with c, several possibilities: 1. this is the first the value in the sequence, the result is b * v 2. this is not the first value in the sequence, and the color is the same as the previous color, dp[c] + a * v 3. this is not the first value in the sequence, we append the num as a successor to a different color. Which color? the color with the biggest dp[c] to make this happen, we need to record the color with the biggest dp[] value. if the color with biggest dp[] value is c, then we should do it with the second biggest dp[] value */ longlong firstOption = b * v; if (dp[c] != LLONG_MIN) { // can be dp[c] // can be b * v(as first value) // can be mx1 + a * v or mx2 + b * v if c == mx // can be mx1 + b * v or mx1 + a * v if c != mx longlong zeroOption = dp[c]; longlong thirdOption; if (c == mc) { thirdOption = max(mx1 + a * v, mx2 + b * v); } else { thirdOption = max(mx1 + b * v, dp[c] + a * v); } dp[c] = max(zeroOption, max(firstOption, thirdOption)); } else { // can be 0 <-- this is wrong, because we need to pick this item, cannot be zero // can be b * v // can be mx1 + b * v if mc != -1 longlong thirdOption = mx1 + b * v; dp[c] = max(firstOption, thirdOption); } if (dp[c] > mx1) { if (c != mc) { mc = c; mx2 = mx1; } mx1 = dp[c]; } elseif (dp[c] > mx2 && c != mc) { mx2 = dp[c]; } } out << mx1 << endl; }
intmain(){ int n, q; in >> n >> q; vector<int> values; vector<int> colors; for (int t = 1; t <= n; t++) { int value; in >> value; values.push_back(value); } for (int t = 1; t <= n; t++) { int color; in >> color; colors.push_back(color); } for (int t = 1; t <= q; t++) { int a, b; in >> a >> b; solve(n, values, colors, a, b); } return0; }