树状数组的运用
具体就是枚举每个裁判,左边比裁判小的个数乘以右边比裁判大的个数,以及左边比裁判大的个数乘以右边小的个数,总和即为结果
/*
ID: sdj22251
PROG: calfflac
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define MAX 100000000
#define LOCA
#define PI acos(-1.0)
using namespace std;
int a[100001], b[100001], data[100001];
int lowbit(int x) //返回二进制下最右边的1,用于树状数组存储和查询时的结构
{
return x & (-x);
}
void calculate1(int x) //由于所有数据是独一无二,并且在100000以内,所以将所有数据处理,用树状数组a预存,所有能被x影响到的数组均改变
{
for(; x < 100001; x += lowbit(x))
a[x]++;
}
void calculate2(int x) //枚举每个裁判时,一个一个的存入树状数组b,方便对当前左侧选手的查询
{
for(; x < 100001; x += lowbit(x))
b[x]++;
}
__int64 sum1(int x) //计算所有数据中比裁判小的个数,从而推出比裁判大的个数
{
__int64 sum = 0;
for(; x > 0; x -= lowbit(x))
sum += a[x];
return sum;
}
__int64 sum2(int x) //计算裁判左侧比裁判小的个数,就能推出右侧,从而推出大的个数
{
__int64 sum = 0;
for(; x > 0; x -= lowbit(x))
sum += b[x];
return sum;
}
int main()
{
#ifdef LOCAL
freopen("ride.in","r",stdin);
freopen("ride.out","w",stdout);
#endif
int n, i, t;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
for(i = 1; i <= n; i++)
{
scanf("%d", &data[i]);
calculate1(data[i]);
}
__int64 ans = 0;
calculate2(data[1]);
for(i = 2; i < n; i++)
{
calculate2(data[i]);
__int64 allsmall = sum1(data[i]);
__int64 nowsmall = sum2(data[i]);
ans += (nowsmall - 1) * ((n - allsmall) - (i - nowsmall));//左边小的乘以右边大的
ans += (i - nowsmall) * (allsmall - nowsmall);//右边小的乘以左边大的
}
printf("%I64d\n", ans);
}
return 0;
}
分享到:
相关推荐
这是一道很不错的题目,即可以用线段树做也可以用树状数组,可谓经典。不过当然了线段树是比较难搞,而树状数组是极其简洁的,构造很简单,下面就分别来介绍一下两种方法...
NULL 博文链接:https://128kj.iteye.com/blog/1744222
NULL 博文链接:https://128kj.iteye.com/blog/1744555
NULL 博文链接:https://128kj.iteye.com/blog/1747400
NULL 博文链接:https://128kj.iteye.com/blog/1745671
NULL 博文链接:https://128kj.iteye.com/blog/1746750
Poj 3342 这是一道树状dp题目,题意是这样的,一个公司,每个人有且仅有一个Boss,除了最大的Boss没有Boss(显然),现在要参加一个聚会,要求参加的人数最多,但是棘手的.......
poj上第1990题目源码,用到了2个树状数组,这题数据结构是关键,想到了题目就很简单了
POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类
西工大POJ习题第五季,数组这类的代码,有截图
原理为:以数链思想,移动数组中的内容 使数组在没有扩充情况下,达成移动的效果 当然,有更简单的,大牛不要笑哦
poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题...
NULL 博文链接:https://128kj.iteye.com/blog/1757060
史上最全poj题目分类及原题 包括:基本算法:贪心、递归、递推、枚举;基本数据结构,链表、栈;动态规划;搜索;高级数据结构:二叉搜索树、线段树、树状数组;数学:数论
大家都用树状数组,但是有人只会用线段树呢? 而且我可以轻易改出一道不能用树状数组的题 在线段树一次次TLE后,有一个ID发帖抱怨 “下次写一个汇编版非递归线段树,再超时?” 可是大家都知道,超时的代码已经2k了...
树状数组解决区间操作_高效 对数组的某个区间进行两种操作:1)求和 2)每个数据加常数。要求:时间复杂度低
POJ第1861题源码 POJ第1861题源码 POJ第1861题源码
北大POJ1159-Palindrome 解题报告+AC代码
C语言 poj npu 西工大 C语言Poj答案全完整打包,给有需要的朋友
poj分类poj分类poj分类poj分类