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;
}