hdu 4000 Fruit Ninja 树状数组

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

Recently, dobby is addicted in the Fruit Ninja. As you know, dobby is a free elf, so unlike other elves, he could do whatever he wants.But the hands of the elves are somehow strange, so when he cuts the fruit, he can only make specific move of his hands. Moreover, he can only start his hand in point A, and then move to point B,then move to point C,and he must make sure that point A is the lowest, point B is the highest, and point C is in the middle. Another elf, Kreacher, is not interested in cutting fruits, but he is very interested in numbers.Now, he wonders, give you a permutation of 1 to N, how many triples that makes such a relationship can you find ? That is , how many (x,y,z) can you find such that x < z < y ?
 
题意描述:给出n个数1~n的随机排列,找出这样的三元组(x,y,z)的个数:x<y<z && an[x]<an[z]<an[y]。
算法分析:对于每个x,求出x后面比an[x]大的数的个数,那么我们可以得到x**(小中大 和 小大中)的个数,之后在往数列后面遍历的时候,减去原来小中大的情况即可。
 #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#define inf 0x7fffffff
using namespace std;
typedef long long LL;
const int maxn=+;
const int MOD=; int n,an[maxn];
LL x[maxn]; int lowbit(int u) {return u&(-u); }
void add(int i,int dd)
{
while (i<=maxn)
{
x[i] += dd;
i += lowbit(i);
}
}
LL sum(int i)
{
LL ret=;
while (i>)
{
ret += x[i];
i -= lowbit(i);
}
return ret;
} int main()
{
int t,ncase=;scanf("%d",&t);
while (t--)
{
scanf("%d",&n);
for (int i= ;i<=n ;i++) scanf("%d",&an[i]);
memset(x,,sizeof(x));
LL ans=;
for (int i= ;i<=n ;i++)
{
add(an[i],);
LL temp1=sum(an[i]-);
LL temp2=n-an[i]-((i-)-temp1);
ans -= temp1*temp2;
if (temp2>=) ans += (temp2-)*temp2/;
}
printf("Case #%d: %I64d\n",ncase++,ans%MOD);
}
return ;
}
上一篇:timesten备份和恢复


下一篇:CentOS 7.4 安装 K8S v1.11.0 集群所遇到的问题