Fruit Ninja
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1675 Accepted Submission(s): 658
Problem Description
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 ?
Input
The first line contains a positive integer T(T <= 10), indicates the number of test cases.For each test case, the first line of input is a positive integer N(N <= 100,000), and the second line is a permutation of 1 to N.
Output
For each test case, ouput the number of triples as the sample below, you just need to output the result mod 100000007.
Sample Input
2 6 1 3 2 6 5 4 5 3 5 2 4 1
Sample Output
Case #1: 10 Case #2: 1
题意:问你 (x,y,z)有多少 x < z < y。
思路:直接算肯定是不行的,不过你可以用x<z<y的加上x<y<z的,再减去x<y<z的情况。
AC代码如下:
#include<cstdio>
#include<cstring>
using namespace std;
long long a[100010];
long long mod=100000007;
long long lowbit(long long x)
{ return x&(-x);
}
long long sum(long long x)
{ long long ret=0;
while(x)
{ ret+=a[x];
x-=lowbit(x);
}
return ret;
}
void update(long long x)
{ while(x<=100005)
{ a[x]++;
x+=lowbit(x);
}
}
int main()
{ int T,t,n,m,i,j;
long long k,ans,qx,qd,hx,hd;
scanf("%d",&T);
for(t=1;t<=T;t++)
{ memset(a,0,sizeof(a));
ans=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
{ scanf("%I64d",&k);
qx=sum(k-1);
qd=i-1-qx;
hd=n-k-qd;
ans-=qx*hd;
ans+=hd*(hd-1)/2;
update(k);
}
ans%=mod;
printf("Case #%d: %I64d\n",t,ans);
}
}