Description
ly有 n 个数,现在她想知道这 n 个数中取出一对数 (x,y) 满足 x%3 <= y%3 的方案数是多少。其中,在这个数列中,x的位置要比y前面。
Input
输入两行,第一行包含一个正整数 n ,表示数的数量。
第二行包含 n 个正整数,ai 表示数列中的第 i 个数。
题目保证 1 <= n <= 10^5, 1 <= ai <=10^9
Output
输出一行,为一个整数,为所求的答案。
Sample Input
4 1 3 4 2
Sample Output
5
注释:mx要用longlong,不然会溢出,答案错误;mx每一次加上比当前小的数的总和(前缀和),开一个数组用来统计余数为0,1,2的个数,那么只要加上当前数的余数小于等于的个数就行。
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[3];
ll n;
ll mx;
int main(){
while(~scanf("%lld",&n)){
memset(a,0,sizeof(a));
mx=0;
for(ll i=0;i<n;i++){
ll w;
scanf("%lld",&w);
ll m=w%3;
if(m==0){
mx+=a[0];
}
if(m==1){
mx+=a[0]+a[1];
}
if(m==2){
mx+=a[0]+a[1]+a[2];
}
a[m]++;
}
printf("%lld\n",mx);
}
}