Question:
A string of pearls can be stolen from the beginning or the end, but the number of pearls to be suspended remains unchanged. The quality must meet the requirements.
Ideas:
Pay attention to the suspended Pearl because it is stolen from the beginning or the end, so the suspended Pearl must be a continuous pearl in the original string.
If you know which part of the hanging pearl is, you can use the second part to find the number of pearls on the table so that the string does not slide down. In this case, the pearl in front of the second part can be stolen.
According to the above analysis, we can enumerate the hanging pearls and then divide them into two parts so that we can determine the complexity of a solution that is constantly updated and optimized. nlogn
There are still two points to add to the practice.
First, the theft must start from the end. After all, leaving more headers will not slide down in advance. This determines that enumeration is performed from the end to the end.
Next, it is also very important to ensure that the string does not slip down during the theft process. This is different from the last state. Therefore, when we enumerate a hanging Point, this will cause the string to slip down in any way. the enumeration should be stopped.
Code:
#include<cstdio>#include<iostream>#include<cstring>#include<string>#include<algorithm>#include<map>#include<set>#include<vector>#include<queue>#include<cstdlib>#include<ctime>#include<cmath>using namespace std;#define N 200010int n, m, K;int w[N], c[N];int sumfw[N], sumbw[N], sumfc[N], sumbc[N];int ansf, ansb, ansc;int main() {int i, l, r, mid, tmp, weight, money;scanf("%d%d%d", &n, &m, &K);for (i = 1; i <= n; i++) {scanf("%d%d", &w[i], &c[i]);sumfw[i] = sumfw[i - 1] + w[i];sumfc[i] = sumfc[i - 1] + c[i];}for (i = n; i >= 1; i--) {sumbw[i] = sumbw[i + 1] + w[i];sumbc[i] = sumbc[i + 1] + c[i];}ansc = 0;for (i = n - m + 1; i >= 1; i--) {weight = sumfw[i + m - 1] - sumfw[i - 1];tmp = 0;l = 1;r = i - 1;while (l <= r) {mid = (l + r) / 2;if ((sumfw[i - 1] - sumfw[mid - 1]) * K >= weight) {tmp = mid;l = mid + 1;} elser = mid - 1;}if (tmp) {money = sumfc[tmp - 1] + sumbc[i + m];if (money > ansc) {ansc = money;ansf = tmp;ansb = i + m - 1;}} elsebreak;}if (ansc) {printf("%d %d\n", n - (ansb - ansf + 1), ansc);i = n - ansb;while (i--)printf("H");i = ansf - 1;while (i--)printf("T");printf("\n");} elseprintf("0 0\n");return 0;}
Sgu 553 Sultan's pearls