CF 86D Powerful array 【分块算法,n*sqrt(n)】
来源:互联网 发布:大数据人工智能的影响 编辑:程序博客网 时间:2024/05/17 19:20
给定一个数列:A1, A2,……,An,定义Ks为区间(l,r)中s出现的次数。
t个查询,每个查询l,r,对区间内所有a[i],求sigma(K^2*a[i])
离线+分块
将n个数分成sqrt(n)块。
对所有询问进行排序,排序标准:
1. Q[i].left /block_size < Q[j].left / block_size (块号优先排序)
2. 如果1相同,则 Q[i].right < Q[j].right (按照查询的右边界排序)
问题求解:
从上一个查询后的结果推出当前查询的结果。(这个看程序中query的部分)
如果一个数已经出现了x次,那么需要累加(2*x+1)*a[i],因为(x+1)^2*a[i] = (x^2 +2*x + 1)*a[i],x^2*a[i]是出现x次的结果,(x+1)^2 * a[i]是出现x+1次的结果。
时间复杂度分析:
排完序后,对于相邻的两个查询,left值之间的差最大为sqrt(n),则相邻两个查询左端点移动的次数<=sqrt(n),总共有t个查询,则复杂度为O(t*sqrt(n))。
又对于相同块内的查询,right端点单调上升,每一块所有操作,右端点最多移动O(n)次,总块数位sqrt(n),则复杂度为O(sqrt(n)*n)。
right和left的复杂度是独立的,因此总的时间复杂度为O(t*sqrt(n) + n*sqrt(n))。
#include <cstdio>#include <iostream>#include <algorithm>#include <cstring>#include <cmath>using namespace std;#define N 200100typedef long long ll;ll a[N], cnt[N*5], ans[N], res;int L, R;struct node { int x, y, l, p;} q[N];bool cmp(const node &x, const node &y) { if (x.l == y.l) return x.y < y.y; return x.l < y.l;}void query(int x, int y, int flag) { if (flag) { for (int i=x; i<L; i++) { res += ((cnt[a[i]]<<1)+1)*a[i]; cnt[a[i]]++; } for (int i=L; i<x; i++) { cnt[a[i]]--; res -= ((cnt[a[i]]<<1)+1)*a[i]; } for (int i=y+1; i<=R; i++) { cnt[a[i]]--; res -= ((cnt[a[i]]<<1)+1)*a[i]; } for (int i=R+1; i<=y; i++) { res += ((cnt[a[i]]<<1)+1)*a[i]; cnt[a[i]]++; } } else { for (int i=x; i<=y; i++) { res += ((cnt[a[i]]<<1)+1)*a[i]; cnt[a[i]]++; } } L = x, R = y;}int main() { int n, t; scanf("%d%d", &n, &t); for (int i=1; i<=n; i++) scanf("%I64d", &a[i]); int block_size = sqrt(n); for (int i=0; i<t; i++) { scanf("%d%d", &q[i].x, &q[i].y); q[i].l = q[i].x / block_size; q[i].p = i; } sort(q, q+t, cmp); memset(cnt, 0, sizeof(cnt)); res = 0; for (int i=0; i<t; i++) { query(q[i].x, q[i].y, i); ans[q[i].p] = res; } for (int i=0; i<t; i++) printf("%I64d\n", ans[i]); return 0;}
- CF 86D Powerful array 【分块算法,n*sqrt(n)】
- CF 86D Powerful array 【分块算法,n*sqrt(n)】
- CF 86D Powerful array 分块算法入门,n*sqrt(n)
- CF 86D Powerful array 分块算法入门,n*sqrt(n)
- CF 86D Powerful array
- 【CF 86D】Powerful array
- Codeforces 86D Powerful array 莫队算法 分块
- [CF 86D] Powerful array · 莫队算法
- Codeforces 86D Powerful array 分块
- codeforces 86D. Powerful array(分块)
- CF 86D Powerful array(莫队)
- 莫队算法 sqrt(n)分块思想
- Codeforces#86D Powerful array(分块暴力)
- 86D - Powerful array
- 【打CF,学算法——四星级】CodeForces 86D Powerful array (莫队算法)
- Yandex.Algorithm 2011 Round 2-D - Powerful array-莫队算法(分块算法)
- 小z的袜子 莫队算法(分块思想) O(N*sqrt(N))
- Codeforces 86D. Powerful array
- Python学习笔记--函数
- 串口 WaitForMultipleObjects函数解释及其用法
- Android(Java):线程
- Oracle-Oracle11g安装图解
- struts2--文件上传和uploadFile拦截器
- CF 86D Powerful array 【分块算法,n*sqrt(n)】
- 自定义UITableView各种函数
- OPENLDAP API 编程简述
- Android中Handler、HandlerThread、AsyncTask的应用
- linux内核同步的介绍
- SQLite创建触发器 CREATE TRIGGER
- iOS高效开源类库
- VisionMobile:2013年Q3移动开发者经济报告(六):第五章、多平台开发者:关键是优先级别
- 文件封装格式和压缩编码格式