我是靠谱客的博主 忧虑朋友,这篇文章主要介绍【算法笔记】求长度为n的序列的全排列包含的总逆序对数目(树状数组求解),现在分享给大家,希望可以做个参考。

本来在想其他的题,好像想偏了,不过最后总结找到了标题所对应的公式。

 

ans(n)=frac{(n-1)*(n+1)!}{6}

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 10000;
#define lowbit(x) ((x)&(-x))
int n, x;
int c[maxn], a[maxn];
void update(int x, int v)
{
    for(int i = x; i <= n; i += lowbit(i))
        c[i] += v;
}
int  getsum(int x)
{
    int ans = 0;
    for(int i = x; i > 0; i -= lowbit(i))
        ans += c[i];
    return ans;
}
int main()
{
    int ans = 0;
    ios::sync_with_stdio(false);
    cin >> n;
    for(int i = 1; i <= n; i++)
        a[i] = i;
    do{
        memset(c, 0, sizeof(c));
        printf("当前排列:");
        for(int i = 1; i <= n; i++)
            cout << a[i] << " ";
        cout << endl;
        int sum = 0;
        for(int i = 1; i <= n; i++)
        {
            update(i, 1);
            sum += getsum(n) - getsum(a[i]);
        }
        printf("逆序对数目:%dn", sum);
        ans += sum;
    }while(next_permutation(a+1, a+1+n));
    cout << ans << endl;
    return 0;
}

 

最后

以上就是忧虑朋友最近收集整理的关于【算法笔记】求长度为n的序列的全排列包含的总逆序对数目(树状数组求解)的全部内容,更多相关【算法笔记】求长度为n内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部