hdu 5147 (树状数组的应用)

来源:互联网 发布:淘宝卖家正在被处罚 编辑:程序博客网 时间:2024/05/16 06:44

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=5147

Sequence II

Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 299    Accepted Submission(s): 131


Problem Description
Long long ago, there is a sequence A with length n. All numbers in this sequence is no smaller than 1 and no bigger than n, and all numbers are different in this sequence.
Please calculate how many quad (a,b,c,d) satisfy:
1. 1a<b<c<dn
2. Aa<Ab
3. Ac<Ad
 

Input
The first line contains a single integer T, indicating the number of test cases.
Each test case begins with a line contains an integer n.
The next line follows n integers A1,A2,,An.

[Technical Specification]
1 <= T <= 100
1 <= n <= 50000
1 <= Ai <= n
 

Output
For each case output one line contains a integer,the number of quad.
 

Sample Input
151 3 2 4 5
 

Sample Output
4
 

Source
BestCoder Round #23
 

Recommend
heyang   |   We have carefully selected several similar problems for you:  5149 5148 5146 5145 5142 
思路:(1)首先暴力枚举啥的肯定不行~

    (2)看看时间1000ms,再看一下数据大小50000,所以肯定有一个O(n)的硬循环,再想想来个O(logn)的处理就差不多了~

    (3)枚举C点,那么[1 , c-1]区间内,满足i<j&&a[i]<a[j] 的个数设为x;  [c,n]区间内比c大的个数设为用;根据乘法原理,x*y就是所要的,那么枚举所有的C点,累加所有的x*y;

#include <iostream>#include <stdio.h>#include <string>#include <string.h>#include <algorithm>const int N=1e5+100;using namespace std;typedef long long ll;int c[N],n;  //树状数组int f[N],g[N];int a[N];int lowbit(int x){  return x&-x;}void update(int x){ while(x<=n) {   c[x]+=1;   x+=lowbit(x); }}int getsum(int x){ int ans=0; while(x>0) {   ans+=c[x];   x-=lowbit(x); } return ans;}int main(){   int T;   scanf("%d",&T);   while(T--)   {     scanf("%d",&n);     for(int i=1;i<=n;i++)scanf("%d",&a[i]);     memset(c,0,sizeof(c));     for(int i=1;i<=n;i++)     {        f[i]=getsum(a[i]);        update(a[i]);     }     memset(c,0,sizeof(c));     for(int i=n;i>=1;i--)     {       update(a[i]);       g[i]=n-i+1-getsum(a[i]);     }     ll ans=0,sum=0;     for(int i=1;i<=n;i++)     {       ans+=sum*g[i];       sum+=f[i];     }     printf("%I64d\n",ans);   }   return 0;}

0 0
原创粉丝点击