【第几小 / 分块】

题目

代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

const int N = 1e5+10;

int a[N];
int br[N], bl[N], id[N], bcnt, L;
vector<int> bs[1010];

int main()
{
  int n;
  cin >> n;
  for(int i = 1; i <= n; i++)
    cin >> a[i];
  
  L = sqrt(n + 1);
  for(int i = 1; i <= n; i += L) //只保证了左边界不越界
  {
    bcnt++;
    bl[bcnt] = i;
    br[bcnt] = min(i + L - 1, n); //这是分块最容易错误的点,就是没有考虑右边界越界
    for(int j = bl[bcnt]; j <= br[bcnt]; j++)
      bs[bcnt].push_back(a[j]), id[j] = bcnt; //想直接用下标访问未初始化的向量,需要resize
  }

  for(int i = 1; i <= bcnt; i++)
    sort(bs[i].begin(), bs[i].end());
    
    int m;
    cin >> m;
    
  for(int i = 1; i <= m; i++)
  {
    int op;
    cin >> op;
    if(op == 1)
    {
      int x, y;
      cin >> x >> y;
      int t = a[x];
      a[x] = y;
      int bid = id[x];
      auto it = lower_bound(bs[bid].begin(), bs[bid].end(), t);
      *it = y;
      sort(bs[bid].begin(), bs[bid].end());
    }
    else if(op == 2)
    {
      int l, r, p;
      cin >> l >> r >> p;
      int cnt = 0;

      if(id[l] == id[r])
      {
        for(int j = l; j <= r; j++)
          if(a[j] < a[p]) cnt++;
      }
      else
      {
        for(int j = id[l] + 1; j < id[r]; j++)
        {
        	auto it = lower_bound(bs[j].begin(), bs[j].end(), a[p]);
        	if(it == bs[j].end()) cnt += br[j] - bl[j] + 1;
        	else cnt += (it - bs[j].begin());
        }
        for(int j = l; j <= br[id[l]]; j++)
          if(a[j] < a[p]) cnt++;
        for(int j = bl[id[r]]; j <= r; j++)
          if(a[j] < a[p]) cnt++;
      }
      cout << cnt + 1 << ' ';
    }
  }
}
相关推荐
不穿格子的程序员21 小时前
从零开始写算法——二分-搜索二维矩阵
线性代数·算法·leetcode·矩阵·二分查找
Kuo-Teng21 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng21 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
2301_800399721 天前
stm32 printf重定向到USART
java·stm32·算法
顾安r1 天前
11.15 脚本算法 加密网页
服务器·算法·flask·html·同态加密
前端小L1 天前
图论专题(四):DFS的“回溯”之舞——探寻「所有可能路径」
算法·深度优先·图论
司铭鸿1 天前
数学图论的艺术:解码最小公倍数图中的连通奥秘
运维·开发语言·算法·游戏·图论
元亓亓亓1 天前
LeetCode热题100--39. 组合总和
算法·leetcode·职场和发展
2401_841495641 天前
【LeetCode刷题】找到字符串中所有字母异位词
数据结构·python·算法·leetcode·数组·滑动窗口·找到字符串中所有字母异位词
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——寻找数组的中心下标
算法·leetcode·职场和发展·结构与算法