acwing基础课第一章离散化

树状数组

241. 楼兰图腾

#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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值