您的位置:首页 > 其它

2018年全国多校算法寒假训练营练习比赛(第五场)逆序数(树状数组)

2018-02-26 02:40 483 查看
链接:https://www.nowcoder.com/acm/contest/77/A
来源:牛客网

时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。比如一个序列为4 5 1 3 2, 那么这个序列的逆序数为7,逆序对分别为(4, 1), (4, 3), (4, 2), (5, 1), (5, 3), (5, 2),(3, 2)。

输入描述:

第一行有一个整数n(1 <= n <= 100000),  然后第二行跟着n个整数,对于第i个数a[i],(0 <= a[i] <= 100000)。

输出描述:

输出这个序列中的逆序数

示例1

输入

5
4 5 1 3 2

输出

7

在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。一个排列中所有逆序总数叫做这个排列的逆序数。
例:
排列523146879的逆序数为:7

5排在首位,逆序数为0;

2前面比2大的数只有5,逆序数为1;
3前面比比3大的数有1个,逆序数为1;
1前面比1大的数有3个,逆序数为3;
4前面比4大的数有1个,逆序数为1;
6前面没有比6大的数,逆序数为0;
8前面没有比8大的数,逆序数为0;
7前面比7的的数有1个,逆序数为1;
9前面没有比9大的数,逆序数为0。
排列523146879的逆序数为:t=0+1+1+3+1+0+0+1+0=7
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 500005;
struct Node
{
int val;
int pos;
};
Node node
;
int c
, reflect
, n;

bool cmp(const Node& a, const Node& b)
{
return a.val < b.val;
}
int lowbit(int x)
{
return x & (-x);
}
void update(int x)
{
while (x <= n)
{
c[x] += 1;
x += lowbit(x);
}
}
int getsum(int x)
{
int sum = 0;
while (x > 0)
{
sum += c[x];
x -= lowbit(x);
}
return sum;
}
int main()
{
while (scanf("%d", &n) != EOF && n)
{
for (int i = 1; i <= n; ++i)
{
scanf("%d", &node[i].val);
node[i].pos = i;
}
sort(node + 1, node + n + 1, cmp);   //排序
for (int i = 1; i <= n; ++i) reflect[node[i].pos] = i;   //离散化
for (int i = 1; i <= n; ++i) c[i] = 0;   //初始化树状数组
long long ans = 0;
for (int i = 1; i <= n; ++i)
{
update(reflect[i]);
ans += i - getsum(reflect[i]);
}
printf("%lld\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐