题目链接:https://www.luogu.com.cn/problem/P1494

一道很经典的莫队模板题,然而每道莫队题的大体轮廓都差不多。

首先莫队是一种基于分块的算法,它的显著特点就是:

能在$O(1)$的时间内从$(l,r)$转换到$(l,r-1),(l-1,r),(l+1,r),(l,r+1)$。

然后它的总复杂度在$O(n\times \sqrt{n})$左右。

这道题中除了莫队的应用外,还需要处理一个组合数$(cul)$和一个$gcd$,然后跑莫队即可。

AC代码:

 #include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm> using namespace std;
typedef long long ll;
const int N=+; int a[N],vis[N];
int ans1[N],ans2[N];
ll ans;
int block; struct node{
int l,r;
int id;
}q[N]; ll cul(ll x){
return x*(x-)/;
} bool cmp(node aa,node bb){
if(aa.l/block==bb.l/block) return aa.r<bb.r;
return aa.l/block<bb.l/block;
} void add(int pos){
vis[a[pos]]++;
ll m=vis[a[pos]];
ans=ans-cul(m-)+cul(m);
} void del(int pos){
vis[a[pos]]--;
ll m=vis[a[pos]];
ans=ans-cul(m+)+cul(m);
} int gcd(int n,int m){
if(m==) return n;
return gcd(m,n%m);
} int main(){
int n,m;
scanf("%d%d",&n,&m);
block=sqrt(n);
for(int i=;i<=n;i++) scanf("%d",&a[i]);
int L=,R=;
for(int i=;i<=m;i++){
scanf("%d%d",&q[i].l,&q[i].r);
q[i].id=i;
}
sort(q+,q+m+,cmp);
for(int i=;i<=m;i++){
while(L<q[i].l){
del(L);
L++;
}
while(L>q[i].l){
L--;
add(L);
}
while(R>q[i].r){
del(R);
R--;
}
while(R<q[i].r){
R++;
add(R);
}
ans1[q[i].id]=ans;
ans2[q[i].id]=cul(q[i].r-q[i].l+);
}
for(int i=;i<=m;i++){
int g=gcd(ans1[i],ans2[i]);
if(ans1[i]==){
printf("0/1\n");
continue;
}
printf("%d/%d\n",ans1[i]/g,ans2[i]/g);
}
return ;
}

AC代码

最新文章

  1. Hadoop笔记系列 一 用Hadoop进行分布式数据处理(1)
  2. 【POJ 2243】Knight Moves
  3. oracle知识点
  4. IIS Server is too busy 解决方法(IIS6)
  5. CodeForces 489C Given Length and Sum of Digits... (贪心)
  6. 几个 JavaScript 奇技淫巧
  7. 20169210《Linux内核原理与分析》第十二周作业
  8. 记一次T-SQL查询优化 索引的重要性
  9. HDOJ-1017 A Mathematical Curiosity(淼)
  10. Python爬虫:常用浏览器的useragent
  11. ZOJ 2794 Just Pour the Water 【矩阵快速幂】
  12. MySQL存储引擎:InnoDB和MyISAM的差别/优劣评价/评测/性能测试
  13. SLAM中的优化理论(一)—— 线性最小二乘
  14. Retrofit原理
  15. MFC学习RepositionBars
  16. 分布式监控系统开发【day38】:报警阈值程序逻辑解析(三)
  17. 人脸检测(1)——HOG特征
  18. PHP之常用设计模式
  19. network / switchboard / jiaohuanji
  20. LeetCode 788 Rotated Digits 解题报告

热门文章

  1. jquery tagsinput监听输入、修改、删除事件
  2. 还不错的Table样式和form表单样式
  3. HDU 1542 Atlantis(扫描线算法)
  4. JavaScript的BOM对象
  5. 题解 【Codeforces988E】Divisibility by 25
  6. Linux - Shell - 参数获取
  7. leetcode 1214 Two Sum BSTs
  8. 阿里云MySQL安装到centos,并链接。
  9. Date、DateFormat、Calendar、Math、System
  10. vue插槽(slot)的模板与JSX写法