R3_A_Out of Sorts

博客详细解析了Bessie牛的冒泡排序算法实现,并使用树状数组来高效计算其代码中moo字符串的打印次数。通过分析冒泡排序过程,博主提出了一种新颖的方法来确定最大逆序对数量,进而预测moo的输出频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Out of Sorts

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

Keeping an eye on long term career possibilities beyond the farm, Bessie the cow has started learning algorithms from various on-line coding websites.

Her favorite algorithm thus far is “bubble sort”. Here is Bessie’s implementation, in cow-code, for sorting an array AA of length NN.

sorted = false

while (not sorted):

sorted = true

moo

for i = 0 to N-2:

​ if A[i+1] < A[i]:

​ swap A[i], A[i+1]

​ sorted = false

Apparently, the “moo” command in cow-code does nothing more than print out “moo”. Strangely, Bessie seems to insist on including it at various points in her code.

Given an input array, please predict how many times “moo” will be printed by Bessie’s code.

Input

The first line of input contains NN (1≤N≤100,0001≤N≤100,000). The next NN lines describe A[0]…A[N−1]A[0]…A[N−1], each being an integer in the range 0…1090…109. Input elements are not guaranteed to be distinct.

Output

Print the number of times “moo” is printed.

Example

input

Copy

5
1
5
3
8
2

output

Copy

4

题目大意

一开始以为是输出逆序对,后来发现不是……白wa了一发

题目大意是按照上面的代码运行,moo会被输出几次。

题目分析

肯定不是逆序对啦,但是还是可以这样考虑的(主要是做的时候不想删掉打好的求逆序对的代码(记得离散化啊))

这段代码说的其实是冒泡排序(废话),直接模拟当然不行。我们先来观察一下冒泡排序的样例。

1 5 3 8 2

1 3 5 2 8

1 3 2 5 8

1 2 3 5 8

上面就是答案4了。我们可以观察到,答案其实就是某个数字最多移动的次数。也就是最大的逆序是多少。我们可以利用树状数组来计算一下这个最大逆序。

代码

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 7;
typedef long long ll;
typedef struct{
  int num, index;
}node;
ll bit[maxn], n;
node arr[maxn];
bool cmp1(node a, node b){
  return a.num < b.num;
}
bool cmp2(node a, node b){
  return a.index < b.index;
}
int lowbit(int x){
  return x & (-x);
}
void add(int x, int k){
  while(x <= n){
    bit[x] += k;
    x += lowbit(x);
  }
}

ll sum(int n){
  ll ans = 0;
  while(n){
    ans += bit[n];
    n -= lowbit(n);
  }
  return ans;
}

int main(int argc, char const *argv[]) {
  ll ans = -1;
  scanf("%d", &n);
  for(int i = 0; i < n; i++){
    scanf("%d", &arr[i].num);
    arr[i].index = i;
  }
  sort(arr, arr + n, cmp1);
  int last = arr[0].num, cnt = 1;
  for(int i = 0; i < n; i++){
    if(last == arr[i].num){
      arr[i].num = cnt;
    }else{
      last = arr[i].num;
      arr[i].num = ++cnt;
    }
  }
  sort(arr, arr + n, cmp2);
  for(int i = 0; i < n; i++){
    ans = max(ans, sum(n) - sum(arr[i].num)) ;
    add(arr[i].num, 1);
  }
  printf("%lld\n", ans + 1);
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值