codeforces 1269E K Integers (二分+树状数组)
2024-10-08 10:54:37
链接:https://codeforces.com/contest/1269/problem/E
题意:给一个序列P1,P2,P3,P4....Pi,每次可以交换两个相邻的元素,执行最小次数的交换移动,使得最后存在一个子段1,2,…,k,这是题目所定义的f(k),题目要求求出所有的f(n),并依次输出。
思路:首先考虑逆序对问题,比如3 2 1 4这个序列,要使其变为1 2 3 4,最小的移动次数是这个序列中逆序对之和,2+1 = 3,逆序对是(3,2) (3,1)(2,1),但是在比如序列3 5 2 1 6 7 4 8 9,求f(4)怎么做?首先是不是把1 2 3 4这个序列聚成在一起,相连在一起,再去计算逆序对个数,两个过程所花费相加就是答案。那么这个题目就分为两个过程,1.聚合n个数字在一起。2.求逆序对的个数,两者花费相加就行。第1个过程如果使得聚合步数最少呢?其实就是求出聚合后的最中间的位置,其他所有的数字向这个位置靠近所花费的移动次数是最少的,这个过程可以用二分做。第2个过程可以用树状数组,也可以用线段树做。输入的时候记录每个数字的位置,建两个树状数组,一个树状数组维护数字出现的次数,用来求逆序对个数,另一个树状数组维护各个数字在原序列的位置。
AC代码:
#include<iostream>
#include<string>
#include<vector>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
ll mod = 1e9+;
const int maxn = 2e5+;
ll t[maxn],cnt[maxn];
ll pos[maxn];
int n;
inline int lowbit(ll x){
return x&(-x);
///算出x二进制的从右往左出现第一个1以及这个1之后的那些0组成数的二进制对应的十进制的数
}
void add(ll *b , int x, int k) {//单点修改
while (x <= n) { //不能越界
b[x] = b[x] + k;
x = x + lowbit(x);
}
}
ll getsum(ll *b,int x) { // a[1]……a[x]的和
ll ans = ;
while (x > ) {
ans = ans + b[x];
x = x - lowbit(x);
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
cin.tie();
cin>>n;
for(int i = ;i<=n;i++){
int t;
cin>>t;
pos[t] = i;
}
ll inv = ;
for(int i = ;i<=n;i++){
inv += (i--getsum(t,pos[i]));
add(t,pos[i],);
add(cnt,pos[i],pos[i]);
if(i==){
cout<<<<" ";
continue;
}
int mid,l = ,r = n;
while(l<=r){
mid = (l+r)>>;
if(getsum(t,mid)*<=i){
l = mid+;
}
else{
r = mid-;
}
}
ll ans = ;
ll cntL = getsum(t,mid);
ll cntR = i - cntL;
ll indexL = getsum(cnt,mid);
ll indexR = getsum(cnt,n)-indexL;
ans+=((mid+mid-cntL+)*cntL)/-indexL;
ans+=(indexR-((mid++(mid+cntR))*cntR)/);
cout<<ans+inv<<" ";
}
return ;
}
最新文章
- AChartEngine 安卓折线图 柱形图等利器
- HDU 4419 Colourful Rectangle --离散化+线段树扫描线
- HealthKit开发教程之HealthKit的主要类型数据
- appium新版本不支持findElementByName,切换到findElementByAndroidUIAutomator
- 如何更快速加载你的JS页面
- Javah生成JNI头文件
- Windbg调试命令详解(1)
- Python3基础 闭包 简单示例
- Jetbrain系列软件配置文件同步
- vue自定义指令directives使用及生命周期
- POJ 1094 Sorting It All Out 【拓扑排序】
- 动态生成web表-asp.net table
- C++中一些类和数据结构的大小的总结
- Android 聊天功能
- Android-fragment-ListView展示-v4支持包
- [洛谷P3292] [SCOI2016]幸运数字
- spring boot 教程(三)配置详解
- [linux]安装code::blocks
- 关于linux的进程中的各个线程cpu占用情况的分析和查看
- cat /proc/iomem
热门文章
- Python 一键安装全部依赖包
- ubantu crontab定时任务设置
- PP: Meta-learning framework with applications to zero-shot time-series forecasting
- ubuntu 部署Django项目+uwsgi+Nginx
- (C语言)学生成绩排序-期末考倒数第二题结构体数组排序
- display: inline-block 布局
- D - How Many Answers Are Wrong HDU - 3038【带权并查集】
- VNote笔记本和画图
- Python之路Day09
- oracle sql 数据库之间导入数据