Codeforces 1167F Scalar Queries 树状数组
昨天没打好像亏疯了, 好像都是sb题啊。
我们先考虑单个区间[L, R], 对于[L, R]中的一个数 x , 我们只需要只要有多少个数字排序之后排到它前面去了就好。
那么整体来说对于 x , 只有比 x 小的数字对 x 有贡献, 我们只要计算出所有比它小的数字, 在所有包含 x 的线段中排到 x 前面的次数。
这个可以用数组数组维护。
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 5e5 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} struct Bit { int a[N]; void modify(int x, int v) { for(int i = x; i < N; i += i & -i) add(a[i], v); } int sum(int x) { LL ans = 0; for(int i = x; i; i -= i & -i) add(ans, a[i]); return ans; } int query(int L, int R) { if(L > R) return 0; return (sum(R) - sum(L - 1) + mod) % mod; } } bit[2]; int n, a[N], id[N]; LL cnt[N]; bool cmp(int x, int y) { return a[x] < a[y]; } int main() { scanf("%d", &n); for(int i = 1; i <= n; i++) scanf("%d", &a[i]), id[i] = i; sort(id + 1, id + 1 + n, cmp); int ans = 0; for(int i = 1; i <= n; i++) { int x = id[i]; LL cnt = 0; add(cnt, 1LL * bit[0].query(1, x - 1) * (n - x + 1) % mod); add(cnt, 1LL * bit[1].query(x + 1, n) * x % mod); add(cnt, 1LL * x * (n - x + 1) % mod); add(ans, cnt * a[x] % mod); bit[0].modify(x, x); bit[1].modify(x, n - x + 1); } printf("%d\n", ans); return 0; } /* */
分类:
Codeforces
, 树状数组
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话