题面
outputstandard 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 A of length N.
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 N (1≤N≤100,000). The next N lines describe A[0]…A[N−1], each being an integer in the range 0…109. Input elements are not guaranteed to be distinct.
Output
Print the number of times “moo” is printed.
题意
这牛写了一个冒泡排序,执行一次代码就嗷一次,给你数组问你嗷几次。
分析
我们都知道冒泡是O(N2),直接用他的函数必然超时。
然后你发现这冒泡每次就是把小的数往前挪1步,所以我们只要排序然后再遍历求出原先位置-当前位置+1(检查嗷一次)的最大值即可。
代码
#include<bits/stdc++.h>
using namespace std;
const int INF=0x3f3f3f3f;
typedef long long ll;
struct node{
int num,index;
}a[100005];
bool cmp(node a,node b){
if(a.num!=b.num) return a.num<b.num;
return a.index<b.index;
}
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&a[i].num),a[i].index=i;
sort(a,a+n,cmp);
int maxn=0;
for(int i=0;i<n;i++){
maxn=max(maxn,a[i].index-i+1);
}
printf("%d\n",maxn);
return 0;
}