Algorithm
The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep".
Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.
In Shapur's opinion the weakness of an army is equal to the number of triplets i, j, k such that i < j < k and ai > aj > ak where ax is the power of man standing at position x. The Roman army has one special trait — powers of all the people in it are distinct.
Help Shapur find out how weak the Romans are.
The first line of input contains a single number n (3 ≤ n ≤ 106) — the number of men in Roman army. Next line contains n different positive integers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 109) — powers of men in the Roman army.
A single integer number, the weakness of the Roman army.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
3
3 2 1
1
3
2 3 1
0
4
10 8 3 1
4
4
1 5 4 3
1
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <stdio.h>
#include <map>
#include <algorithm>
#include <memory.h>
using namespace std;
typedef long long ll;
int const N = 1e6 + 1;
int n, a[N], tmpa[N], seg[4 * N], mx[N], mn[N];
map<int, int> mp;
int tar;
void update(int idx, int l, int r) {
if(tar < l || tar > r)
return;
if(l == r) {
seg[idx] = 1;
return;
}
int mid = (l + r) >> 1;
update(idx << 1, l, mid);
update((idx << 1) + 1, mid + 1, r);
seg[idx] = seg[idx << 1] + seg[(idx << 1) + 1];
}
int s, e;
int get(int idx, int l, int r) {
if(e < l || s > r)
return 0;
if(l >= s && r <= e)
return seg[idx];
int mid = (l + r) >> 1;
return get(idx << 1, l, mid) + get((idx << 1) + 1, mid + 1, r);
}
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; ++i) {
scanf("%d", a + i);
tmpa[i] = a[i];
}
sort(tmpa + 1, tmpa + n + 1);
for(int i = 1, cnt = 1; i <= n; ++i)
if(!mp.count(tmpa[i]))
mp[tmpa[i]] = cnt++;
for(int i = 1; i <= n; ++i)
a[i] = mp[a[i]];
memset(seg, 0, sizeof seg);
tar = a[1];
update(1, 1, n);
for(int i = 2; i < n; ++i) {
s = a[i] + 1, e = 1e6;
mx[i] = get(1, 1, n);
tar = a[i];
update(1, 1, n);
}
memset(seg, 0, sizeof seg);
tar = a[n];
update(1, 1, n);
for(int i = n - 1; i > 1; --i) {
s = 1, e = a[i] - 1;
mn[i] = get(1, 1, n);
tar = a[i];
update(1, 1, n);
}
long long res = 0;
for(int i = 1; i <= n; ++i)
res += (1LL * mx[i] * mn[i]);
printf("%lld\n", res);
return 0;
}
Copy The Code &
Try With Live Editor
Input
3 2 1
Output
Demonstration
Codeforcess Solution Enemy is weak,E. Enemy is weak C,C++, Java, Js and Python ,E. Enemy is weak,Codeforcess Solution