-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpingPong_UVA1428.cpp
101 lines (77 loc) · 1.79 KB
/
pingPong_UVA1428.cpp
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
91
92
93
94
95
96
97
98
99
100
101
#include <bits/stdc++.h>
using namespace std;
ifstream fin("pingPong_UVA1428.in");
ofstream fout("pingPong_UVA1428.out");
class fenwickTree
{
private:
int lowbit(int x)
{
return x & (-x);
}
public:
vector<int> a;
vector<int> s;
fenwickTree(vector<int> & in)
{
int n = in.size();
a.assign(n, 0);
s.assign(n, 0);
}
void update(int k, int delta)
{
int n = s.size() - 1;
a[k] += delta;
for (int i = k; i <= n; i += lowbit(i))
{
s[i] += delta;
}
}
int query(int k)
{
int n = s.size() - 1;
int ans = 0;
for (int i = k; i >= 1; i -= lowbit(i))
{
ans += s[i];
}
return ans;
}
int sum(int i, int j)
{
return query(j) - query(i - 1);
}
};
int main()
{
int testCase; fin >> testCase;
for (int t = 1; t <= testCase; ++t)
{
int n; fin >> n;
vector<int> s(100001, 0);
fenwickTree treeL(s), treeR(s);
vector<int> a(n, 0), l(n, 0), r(n, 0);
for (int i = 0; i <= n - 1; ++i)
{
fin >> a[i];
}
for (int i = 0; i <= n - 1; ++i)
{
treeL.update(a[i], 1);
l[i] = treeL.query(a[i]);
}
for (int i = n - 1; i >= 0; --i)
{
treeR.update(a[i], 1);
r[i] = treeR.query(a[i]);
}
long long ans = 0;
for (int i = 0; i <= n - 1; ++i)
{
int minL = l[i] - 1, minR = r[i] - 1;
ans += (minL * (n - i - 1 - minR) + (i - minL) * minR);
}
fout << ans << '\n';
}
return 0;
}