HOJ2275 Number sequence

来源:互联网 发布:算法爱好者 公众号 编辑:程序博客网 时间:2024/06/06 13:09

Number sequence

My Tags  (Edit)
 Source : SCU Programming Contest 2006 Final Time limit : 1 sec Memory limit : 64 M

Submitted : 1632, Accepted : 440

Given a number sequence which has N element(s), please calculate the number of different collocation for three number Ai, Aj, Ak, which satisfy that Ai < Aj > Ak and i < j < k.

Input

The first line is an integer N (N <= 50000). The second line contains N integer(s): A1, A2, ..., An(0 <= Ai <= 32768).

Output

There is only one number, which is the the number of different collocation.

Sample Input
51 2 3 4 1
Sample Output

6

这题可以用树状数组做,开两个一维的树状数组分别记录当前点前面的比这点小的个数和后面比这点大的个数。

#include<iostream>#include<stdio.h>#include<string.h>#include<math.h>#include<vector>#include<map>#include<queue>#include<stack>#include<string>#include<algorithm>using namespace std;#define maxn 50005#define ll long longint b1[maxn],b2[maxn],a[maxn];int lowbit(int x){return x&(-x);}void update1(int pos,int num){while(pos<=maxn){b1[pos]+=num;pos+=lowbit(pos);}}int getsum1(int pos){int num=0;while(pos>0){num+=b1[pos];pos-=lowbit(pos);}return num;}void update2(int pos,int num){while(pos<=maxn){b2[pos]+=num;pos+=lowbit(pos);}}int getsum2(int pos){int num=0;while(pos>0){num+=b2[pos];pos-=lowbit(pos);}return num;}int main(){int n,m,i,j;ll num=0;while(scanf("%d",&n)!=EOF){memset(b1,0,sizeof(b1));memset(b2,0,sizeof(b2));for(i=1;i<=n;i++){scanf("%d",&a[i]);a[i]++;if(i==1){update1(a[i],1);continue;}update2(a[i],1);}num=0;for(i=2;i<=n-1;i++){num+=getsum1(a[i]-1)*getsum2(a[i]-1);update1(a[i],1);update2(a[i],-1);}printf("%lld\n",num);}return 0;}


0 0
原创粉丝点击