树状数组
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define int long long
const int N = 200010;
typedef long long LL;
int n;
int y[N], tr[N];
int dp1[N], dp2[N];
int lowbit(int x)
{
return x&-x;
}
void update(int x, int c)
{
for(int i = x;i <= n;i += lowbit(i))
{
tr[i] += c;
}
}
LL query(int x)
{
LL res = 0;
for(int i = x; i; i -= lowbit(i))
{
res+= tr[i];
}
return res;
}
main()
{
LL ans1=0, ans2=0;
cin >> n;
for(int i = 1 ; i <= n; i ++)
{
scanf("%lld", &y[i]);
update(y[i], 1);
dp1[i] = query(n) - query(y[i]);
dp2[i] = query(y[i] - 1);
}
memset(tr, 0, sizeof tr);
for(int i = 1; i <=n; i ++)
{
update(y[i], dp1[i]);
ans1 += query(y[i] - 1);
}
memset(tr, 0, sizeof tr);
for(int i = 1; i <= n; i ++)
{
update(y[i], dp2[i]);
ans2 += query(n) - query(y[i]);
}
cout << ans1 << " " << ans2 << endl;
}
数组离散化
对与值很大的数字,可以对其进行离散化,使其大小关系保持不变
vector<int> alls; // 存储所有待离散化的值
sort(alls.begin(), alls.end()); // 将所有值排序
alls.erase(unique(alls.begin(), alls.end()), alls.end()); // 去掉重复元素
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
int n;
const int N = 500010;
int a[N];
int tr[N];
vector<int> all;
int lowbit(int x)
{
return x&-x;
}
void add(int x, int c)
{
for(int i = x; i <= n; i += lowbit(i))
tr[i] += c;
}
int query(int x)
{
int res = 0;
for(int i = x; i; i -= lowbit(i))
res += tr[i];
return res;
}
int main()
{
while(1)
{
memset(tr, 0, sizeof tr);
memset(a, 0, sizeof a);
all.clear();
LL ans = 0;
cin >> n;
if(!n)break;
for(int i = 0; i < n; i ++)
{
cin >> a[i];
all.push_back(a[i]);
}
sort(all.begin(), all.end());
all.erase(unique(all.begin(), all.end()), all.end());
for(int i = 0; i < n; i ++)
{
int x = lower_bound(all.begin(), all.end(), a[i]) - all.begin() + 1;//找到a[i]对应的离散化数值。
ans += query(all.size()) - query(x);//找到所有比x的值。
add(x, 1);
}
printf("%lld\n", ans);
}
}