@PAT顶级 1010 Lehmer Code (35 分)
1010 Lehmer Code (35 分)
利用树状数组解决问题,注意到数组中会出现很大的数,所以需要将数组值进行转换,利用排序后元素所在位置将原数组转换至1~n的区间。
在利用快排对数组进行排序时,会发现一个点超时。对代码进行分析之后确定排序对时间影响十分大(把排序代码注释掉就不会超时),所以利用map对数组进行了排序。
#include<stdio.h>
#include<vector>
#include<map>
using namespace std;
int lowbit(int x) {
return x&(-x);
}
void update(int x,vector<int> &c) {
while (x < c.size()) {
c[x]++;
x += lowbit(x);
}
}
int getsum(int x, vector<int> &c) {
int sum = 0;
while (x > 0) {
sum += c[x];
x -= lowbit(x);
}
return sum;
}
int main() {
int n;
scanf("%d", &n);
vector<int> res(n+1);
vector<int> tmp(n+1);
map<int, int> mp;
for (int i = 1; i <= n; ++i) {
scanf("%d", &tmp[i]);
mp[tmp[i]] = 1;
}
int k = 1;
for (auto &q : mp) {
q.second = k++;
}
vector<int> c(k, 0);
for (int i = 1; i < k; ++i) {
tmp[i] = mp[tmp[i]];
}
for (int i = n; i > 0; --i) {
update(tmp[i], c);
res[i] = getsum(tmp[i]-1, c);
}
for (int i = 1; i <= n; ++i) {
printf("%d", res[i]);
if (i != n) printf(" ");
}
}