Ping pong
Descriptionide
N(3<=N<=20000) ping pong players live along a west-east street(consider the street as a line segment). Each player has a unique skill rank. To improve their skill rank, they often compete with each other. If two players want to compete, they must choose a referee among other ping pong players and hold the game in the referee's house. For some reason, the contestants can't choose a referee whose skill rank is higher or lower than both of theirs. The contestants have to walk to the referee's house, and because they are lazy, they want to make their total walking distance no more than the distance between their houses. Of course all players live in different houses and the position of their houses are all different. If the referee or any of the two contestants is different, we call two games different. Now is the problem: how many different games can be held in this ping pong street?
Inputthis
The first line of the input contains an integer T(1<=T<=20), indicating the number of test cases, followed by T lines each of which describes a test case.
Every test case consists of N + 1 integers. The first integer is N, the number of players. Then N distinct integers a1, a2 ... aN follow, indicating the skill rank of each player, in the order of west to east. (1 <= ai <= 100000, i = 1 ... N). Outputspa
For each test case, output a single line contains an integer, the total number of different games.
Sample Inputcode 1 3 1 2 3 Sample Outputblog 1 Source排序 |
首先簡要說明題意,給定一個不存在重複數的序列,請問其中,有多少種可能,挑三個數出來,按位置排列,知足單增或者單減ip
首先咱們先考慮,要求出每一個數與它前面的數構成的順序對數a,逆序對數b;與它後面的數構成的順序對數c,逆序對數dget
ans=a*c+b*d;input
由於前面的一個順序對與後面的一個順序對 重合一個數,三個數,恰好知足題目的條件。string
這裏再解釋一下如何求a,b,c,d:
先把全部數排序而且記錄位置。
而後咱們只須要將數從大到小,每一個數所在的位置添加1,而後對於這個數的b和c只須要分別統計前綴和與後綴和便可
反向從小到大能夠求出a,d
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N=20005; struct A { int z,id; bool operator<(const A a)const { return z<a.z; } }a[N]; int c[N],jl[N][2],n; void add(int x) { for(;x<=n;x+=x&-x) ++c[x]; } int askk(int x) { int re=0; for(;x;x-=x&-x) re+=c[x]; return re; } int main() { int t; scanf("%d",&t); while(t--) { long long ans=0; scanf("%d",&n); for(int i=1;i<=n;++i) scanf("%d",&a[a[i].id=i].z); sort(a+1,a+n+1); memset(c,0,sizeof(c)); for(int i=1;i<=n;++i) { add(a[i].id); jl[i][0]=askk(a[i].id-1); jl[i][1]=askk(n)-askk(a[i].id); } memset(c,0,sizeof(c)); for(int i=n;i;--i) { add(a[i].id); ans+=(long long)jl[i][1]*askk(a[i].id-1); ans+=(long long)jl[i][0]*(askk(n)-askk(a[i].id)); } printf("%lld\n",ans); } return 0; }