树状数组30分WA,求助

P1908 逆序对

BLX32M_10 @ 2021-12-22 17:18:51

#include <algorithm>
#include <cstdio>
using std::stable_sort;

int n, c[500005], lsh[500005], a[500005];
long long ans, sum;

int lowbit(int x)
{
    return x & (-x);
}

void add(int x)
{
    while (x <= n)
        c[x]++, x += lowbit(x);
}

int query(int x)
{
    sum = 0;
    while (x > 0)
        sum += c[x], x -= lowbit(x);
    return sum;
}

bool cmp(int x, int y)
{
    return a[x] > a[y];
}

int main()
{
    scanf("%d", &n);

    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &a[i]);
        lsh[i] = i;
    }

    stable_sort(lsh + 1, lsh + n + 1, cmp);

    for (int i = 1; i <= n; i++)
    {
        add(lsh[i]);
        ans += query(lsh[i] - 1);
    }

    printf("%lld", ans);
    return 0;
}

by BLX32M_10 @ 2021-12-22 17:19:11

改好了


by OldVagrant @ 2021-12-22 17:21:33

@Brooksx 你这求的是正序对啊


by BLX32M_10 @ 2021-12-22 17:22:37

@z_z_y 所以说为啥还30分呢


by OldVagrant @ 2021-12-22 17:23:08

@Brooksx 有可能正序对数量和逆序对数量一样啊


by BLX32M_10 @ 2021-12-22 17:24:00

那,把 > 改成 < 直接全WA???


by BLX32M_10 @ 2021-12-22 17:24:11

@z_z_y


by OldVagrant @ 2021-12-22 17:25:30

@Brooksx 不是这个的问题,你应该倒着遍历

for(int i=n;i;i--){
    add;
   更新ans
    }

by BLX32M_10 @ 2021-12-22 17:29:43

AC了 蓝钩大佬%%%


|