HDU 2689 Sort it 解题报告 树状数组

HDU 2689 Sort it 解题报告 树状数组

解题思路:用树状数组处理逆序数。这种用二进制处理的方法真的很有意思。
树状数组讲解
这是我觉得讲的比较好的一篇了,还有其他的博客也讲的很好,更细致更深入,但我选的这篇有基础的使用公式,我比较喜欢。看懂我给的链接,下面的代码理解就十分容易了。
核心思路就是不断插入数字,每次都统计出数组中比这个数字小的数的数量,并累加起来就得到答案了。
对于这题来说,暴力不超时,但是最好还是用树状数组做。
在这里插入图片描述

#include<iostream>
#include<math.h>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
#include<string.h>
#include<map>
#include<stack>
#include<stdio.h>
#include<cstdio>
#include<stdlib.h>
#include<fstream>
#include<sstream>
#include<set>
#pragma warning(disable:4996)
#define INF 0x3f3f3f3f
#define ll long long
#define PI acos(-1.0)
const int N = 100005;
const int maxn = 1e9;
using namespace std;
int n;
int tree[1010];
int lowbit(int x)
{
	return x & (-x);
}
void update(int i, int x)
{
	while (i <= n)
	{
		tree[i] += x;
		i += lowbit(i);
	}
}
int getsum(int i)
{
	int sum = 0;
	while (i >= 1)
	{
		sum += tree[i];
		i -= lowbit(i);
	}
	return sum;
}
int main()
{
	while (scanf("%d", &n) != EOF )
	{
		
		int tem,sum=0;
		memset(tree, 0, sizeof(tree));
		for (int i = 1; i <= n; i++)
		{
			scanf("%d", &tem);
			sum += getsum(n) - getsum(tem);
			update(tem, 1);
		}
		printf("%d\n", sum);
	}
}


发布了64 篇原创文章 · 获赞 0 · 访问量 1463

猜你喜欢

转载自blog.csdn.net/weixin_45566331/article/details/104378192