跳转链接

题目描述

给定一个序列, 求出将此序列变换为单调递增单调递减 或者先增后减

样例1

输入
7
3 1 4 1 5 9 2
输出
3

样例2

输入
9
10 4 6 3 15 9 1 1 12
输出
8

分析

本题相当于是有一个峰值, 峰值两边的都单调递减

我们可以用树状数组求出对于所有的数字处于峰值左边或者右边所需要的交换次数

对于这两种情况取一个最小值即可

CODE

#include <iostream>
#define lowbit(i) i & -i
#define mset(a) for(int i = 0; i <= px; i ++ ) a[i] = 0 using namespace std; const int N = 1e5 + 10; int n, px;
int a[N], tr[N], cnt[N]; void add(int x) {
for(int i = x; i <= px; i += lowbit(i) ) tr[i] ++;
} int sum(int x) {
int ans = 0;
for(int i = x; i; i -= lowbit(i)) ans += tr[i];
return ans;
} int main() {
ios::sync_with_stdio(false), cin.tie(0);
cin >> n;
for(int i = 1; i <= n; i ++ ) {
cin >> a[i];
px = max(a[i], px);
} for(int i = 1; i <= n; i ++ ) {
cnt[i] = sum(px) - sum(a[i]);
add(a[i]);
}
mset(tr);
for(int i = n; i; i -- ) {
cnt[i] = min(sum(px) - sum(a[i]), cnt[i]);
add(a[i]);
}
long long ans = 0;
for(int i = 1; i <= n; i ++ ) ans += cnt[i];
cout << ans << endl;
return 0;
}

随机推荐

  1. C# 基础(更新中)

    Data Structure There're two types of variables in C#, reference type and value type. Enum: enum Colo ...

  2. codeforce 597C-Subsequences(dp+树状数组)

    题目和南阳那道题一样链接http://www.cnblogs.com/zzuli2sjy/p/4943774.html 代码: 1 #include<stdio.h> 2 #include ...

  3. hdu-1593 find a way to escape(贪心,数学)

    思路:两个人都要选取最优的策略. 先求外层那个人的角速度,因为他的角速度是确定的,再求内层人的当角速度和外层人一样时的对应的圆的半径r1.外层圆的半径为d; 那么如果r1>=外围圆的半径,那么肯 ...

  4. Codeforces 888E:Maximum Subsequence(枚举,二分)

    You are given an array a consisting of n integers, and additionally an integer m. You have to choose ...

  5. HashMap及LinkedHashMap

    HashMap是Map族中最为常用的一种,也是Java Collection Framework的重要成员.HashMap和双向链表合二为一即是LinkedHashMap.所谓LinkedHashMa ...

  6. Improving Adversarial Robustness Using Proxy Distributions

    目录 概 主要内容 proxy distribution 如何利用构造的数据 Sehwag V., Mahloujifar S., Handina T., Dai S., Xiang C., Chia ...

  7. Android开发 ListView(垂直滚动列表项视图)的简单使用

    效果图: 使用方法: 1.在布局文件中加入ListView控件: <?xml version="1.0" encoding="utf-8"?> &l ...

  8. .net core中的Options重新加载机制

    Options是.net core提出的一种辅助配置机制,即选项. 目前,我们可以使用的Options有五种(源码): IOptionsFactory<>:Options的创建工厂(Sin ...

  9. RSA非对称加密算法实现:C#

    RSA是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.当时他们三人都在麻省理工学院工作.RSA ...

  10. .net core使用rabbitmq消息队列

    看博文的朋友,本文有些过时了,还有些BUG,如果想了解更多用法,看看这篇吧:.net core使用rabbitmq消息队列 (二) 首先,如果你还没有安装好rabbitmq,可以参考我的博客: Ubu ...