中级农民
- 积分
- 233
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2020-11-25
- 最后登录
- 1970-1-1
|
你說的是對的。我貼錯了我的代碼版本,因為是在code裡面調試,試過好幾種解法。- // its total contribution, and sum them up.
- // idxM1[i]: for nums[i], the index of nums[i] - 1 <= it bounds one side the min-set can expand
- // lSm[i]: for nums[i], the biggest index with number less than nums[i] - 1
- // rSm[i]: for nums[i], the smallest index with number less than nums[i] - 1
- // illustration:
- /* idx 0 1 2 3 4 5
- num 2 4 3 1 6 5
- idxM1 3 2 0 -1 5 1 <- for 4, the index for 4-1=3 is 2, for 1, it's the smallest so -1
- lSm -1 0 -1 -1 3 3 <- for 4, the biggest index would be 0 to form min-set [2 4]
- rSm -1 3 3 -1 -1 -1 <- for 4, the smallest index would be 3 to form min-set [4 3 1], of course since 3 is in it
-
- */
- long long countImbalance(vector<int>& nums) {
- int n = nums.size();
- vector<int> lSm(n, -1), rSm(n, -1), num2idx(n, -1), idxM1(n, -1);
- // num2idx[i] stores the index of i - 1
- // num2idx should be: {3, 0, 2, 1, 5, 4}
- for (int i = 0; i < n; ++i) {
- num2idx[nums[i] - 1] = i;
- }
- // idxM1 should be {3, 2, 0, -1, 5, 1}
- // for nums[i], the index for nums[i] - 1 is idxM1[nums[i] - 1]
- for (int i = 0; i < n; ++i) {
- if (nums[i] == 1) continue;
- idxM1[i] = num2idx[nums[i] - 2];
- }
- // now we should get the closest elem that is next to nums[i], on both sides
- stack<int> stk{};
- // lSm should be: {-1, 0, -1, -1, 3, 3}
- for (int i = 0; i < n; ++i) {
- while (stk.size() && (nums[stk.top()] > nums[i] || nums[stk.top()] == nums[i] - 1)) stk.pop();
- if (stk.size()) lSm[i] = stk.top();
- stk.push(i);
- }
- // rSm should be: {-1, 3, 3, -1, -1}
- while (stk.size()) stk.pop();
- for (int i = n - 1; i >= 0; --i) {
- while (stk.size() && (nums[stk.top()] > nums[i] || nums[stk.top()] == nums[i] - 1)) stk.pop();
- if (stk.size()) rSm[i] = stk.top();
- stk.push(i);
- }
- long long ttl = 0;
- for (int i = 0; i < n; ++i) {
- int rChoice = 0, lChoice = 0;
- long long subttl = 0;
- if (idxM1[i] < i) {
- if (rSm[i] != -1) {
- // ... 3 4 1 ... [n=7]
- rChoice = n - rSm[i];
- lChoice = i - idxM1[i];
- subttl += lChoice * rChoice;
- }
- if (lSm[i] > idxM1[i]) {
- // ... 3 1 4 ... [n=7]
- lChoice = lSm[i] - idxM1[i];
- rChoice = n - i;
- subttl += lChoice * rChoice;
- }
- if (rSm[i] != -1 && lSm[i] > idxM1[i]) subttl--;
- }
- else { // idxM1[i] > i
- if (lSm[i] != -1) {
- // ... 1 4 3 ... [n=7]
- rChoice = idxM1[i] - i;
- lChoice = lSm[i] + 1;
- subttl += lChoice * rChoice;
- }
- if (rSm[i] != -1 && rSm[i] < idxM1[i]) {
- // ... 1 4 3 ... [n=7]
- lChoice = i + 1;
- rChoice = idxM1[i] - rSm[i];
- subttl += lChoice * rChoice;
- }
- if (lSm[i] != -1 && rSm[i] != -1 && rSm[i] < idxM1[i]) subttl--;
- }
- cout << nums[i] << ":" << (subttl > 0 ? subttl : 0) << endl;
- ttl += (subttl > 0 ? subttl : 0);
- }
- return ttl;
- }
复制代码
补充内容 (2022-09-30 14:38 +8:00):
前半部分都是一樣的。從那個算ttl的地方開始有不同。這個調試版本能夠打印出來每一個數字對ttl的貢獻,可能如果還有bug的話找起來會方便一點。 |
|