csp-J代码模板

· · 个人记录

include<bits/stdc++.h>

using namespace std;

const int N = 1e5 + 10;

int main(){

// 文件名必须和题目要求完全一致,区分大小写
freopen("题目名.in", "r", stdin);
freopen("题目名.out", "w", stdout);
// 加速cin/cout,避免超时
ios::sync_with_stdio(false);
cin.tie(0);
// 你的核心代码写在这里
return 0;

}

📊排序模板

// 1-based数组升序排序(最常用)

sort(a + 1, a + n + 1);

// 降序排序

sort(a + 1, a + n + 1, greater<int>());

// 自定义结构体双关键字排序

struct Node{int x, y;};

sort(a + 1, a + n + 1, [](const

Node& p, const Node& q){

if(p.x != q.x) return p.x < q.x;

return p.y < q.y;

});

🧮 前缀和&差分模板

这是J组T2高频考点,掌握了就能O(1)算区间和,不用暴力循环:

一维前缀和:

cpp long long s[N]; // 开long long防溢出

for(int i = 1; i <= n; i++){

cin >> a[i];
s[i] = s[i-1] + a[i];

} // 查询[l, r]区间和

cout << s[r] - s[l-1] << '\n';

一维差分: cpp

long long d[N];

// 区间[l, r]所有元素加v

d[l] += v; d[r+1] -= v;

// 最后还原原数组 for(int i = 1; i <= n; i++){

a[i] = a[i-1] + d[i];

}

ok谢谢文心