本文主要是介绍Sona(莫队+离散化),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Sona, Maven of the Strings. Of cause, she can play the zither.
Sona can’t speak but she can make fancy music. Her music can attack, heal, encourage and enchant.
There’re an ancient score(乐谱). But because it’s too long, Sona can’t play it in a short moment. So Sona decide to just play a part of it and revise it.
A score is composed of notes. There are 109 kinds of notes and a score has 105 notes at most.
To diversify Sona’s own score, she have to select several parts of it. The energy of each part is calculated like that:
Count the number of times that each notes appear. Sum each of the number of times’ cube together. And the sum is the energy.
You should help Sona to calculate out the energy of each part.
Input
This problem contains several cases. And this problem provides 2 seconds to run.
The first line of each case is an integer N (1 ≤ N ≤ 10^5), indicates the number of notes.
Then N numbers followed. Each number is a kind of note. (1 ≤ NOTE ≤ 10^9)
Next line is an integer Q (1 ≤ Q ≤ 10^5), indicates the number of parts.
Next Q parts followed. Each part contains 2 integers Li and Ri, indicates the left side of the part and the right side of the part.
Output
For each part, you should output the energy of that part.
Sample Input
8
1 1 3 1 3 1 3 3
4
1 8
3 8
5 6
5 5
Sample Output
128
72
2
1
题意: 给定N个数和m次查询,查询给定范围内不同种类颜色出现次数的立方和。
题解:莫队算法加离散化
代码如下
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
long long a[200010],b[200010],c[200010];
long long sum,k,d[200010];
struct z{int l,r,id,p;
} s[200010];
bool cmp(z a,z b) //对查询进行排序
{if(a.p==b.p)return a.r<b.r;elsereturn a.p<b.p;
}
void add(int x,int y) //随着范围移动数据加减
{if(x==0)return ;sum=sum-c[a[x]]*c[a[x]]*c[a[x]]; //减去原来的c[a[x]]=c[a[x]]+y;sum=sum+c[a[x]]*c[a[x]]*c[a[x]]; //加上现在的
}
int main()
{int n,m;while(~scanf("%d",&n)&&n){int i,j,l=0,r=0;for(i=1;i<=n;i++){scanf("%lld",&a[i]);d[i]=a[i];c[i]=0;}scanf("%d",&m);sort(d+1,d+1+n);k=unique(d+1,d+n+1)-(d+1);for(i=1;i<=n;i++)a[i]=lower_bound(d+1,d+1+k,a[i])-d; //离散化进行优化 int x=sqrt(n);for(i=0;i<m;i++){scanf("%d%d",&s[i].l,&s[i].r);s[i].id=i;s[i].p=s[i].l/x;}sort(s,s+m,cmp);sum=0;for(i=0;i<m;i++) //莫队 {while(l<s[i].l) add(l++,(-1));while(l>s[i].l) add(--l,1);while(r>s[i].r) add(r--,(-1));while(r<s[i].r) add(++r,1);b[s[i].id]=sum;}for(i=0;i<m;i++)printf("%lld\n",b[i]);}return 0;
}
这篇关于Sona(莫队+离散化)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!