MYF

HDU 5792 World is Exploding

题目链接

HDU 5792

题目类型:树状数组求解逆序数

题目来源:2016 Multi-University Training Contest 5

题目分析

题目大意

给出$n$个数,问有多少个组合,使$a \neq b \neq c \neq d, 1 \lt a \lt b \leq n, 1 \leq c \lt d \leq n, A{a} \lt A{b}, A{c} \gt A{d}$

解析

很明显,先找出来所有$A{a} \lt A{b}$的情况,再找出来所有$A{c} \gt A{d}$,相乘再减去数字重复的部分,分析一下,当重复的情况必然只有三个不同的数字,这三个不同的数字满足上面的两个条件,所以我们要把他减去。(a,b)和(c,d)两两组和,共有4种情况。我们可以使用树状数组求出来每个数左边比他大的数量LeftBig,左边比他小的数量LeftSmall,右边比他大的数量RightBig,右边比他小的数量RightSmall。左边的两个数和右边的两个数分别相乘求和即为重复的情况的数量,求出总的顺序数和逆序数然后相乘减去这些重复的情况即为所求。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <iomanip>
#include <bitset>
#include <cstring>
#include <iostream>
#include <deque>
#include <algorithm>
#define Memset(a,val) memset(a,val,sizeof(a))
#define PI acos(-1)
#define PB push_back
#define MP make_pair
#define rt(n) (i == n ? '\n' : ' ')
#define hi printf("Hi----------\n")
#define IN freopen("input.txt","r",stdin);
#define OUT freopen("output.txt","w",stdout);
#define debug(x) cout<<"Debug : ---"<<x<<"---"<<endl;
#define debug2(x,y) cout<<"Debug : ---"<<x<<" , "<<y<<"---"<<endl;
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
const int maxn=50000+5;
const int mod=1000000007;
const int INF=0x3f3f3f3f;
const double eps=1e-8;
ll rb[maxn],rs[maxn],lb[maxn],ls[maxn];
ll a[maxn],t[maxn],c[maxn];
ll n,nx,sx,ans,tmp;
ll lowbit(ll x){
return x&(-x);
}
void update(ll pos,ll val){
while (pos<=n) {
c[pos]+=val;
pos+=lowbit(pos);
}
}
ll sum(ll pos){
ll ans=0;
while (pos>0) {
ans+=c[pos];
pos-=lowbit(pos);
}
return ans;
}
int main(){
while (scanf("%lld",&n)!=EOF) {
for (ll i=1; i<=n; i++) {
scanf("%lld",&tmp);
a[i]=t[i]=tmp;
}

nx = sx = 0;
ans=0;

sort(t+1, t+1+n);
ll cnt=unique(t+1, t+n+1)-t-1;
for (ll i=1; i<=n; i++){
a[i]=lower_bound(t+1, t+1+cnt, a[i])-t;
}

memset(c, 0, sizeof(c));
for (ll i = 1 ; i<=n; i++) {
update(a[i], 1);
lb[i]= i - sum(a[i]); //左边大于a[i]的数的个数
ls[i] = sum(a[i]-1); //左边小于a[i]的数的个数
sx +=ls[i]; //顺序数的累加
}
memset(c, 0, sizeof(c));
for (ll i = n; i >= 1; i--) {
update(a[i], 1);
rs[i] = sum(a[i]-1); //右边小于a[i]的数的个数
rb[i] = n - sum(a[i]) - i + 1; //右边大于a[i]的数的个数
nx += rs[i]; //逆序数的累加
}

ans = nx * sx;
for (ll i = 1; i <= n; i++)
ans -= ( rb[i] + ls[i] ) * ( rs[i] + lb[i] );

cout<<ans<<endl;
}
}