题面:
Out of Sorts
time limit per test:1 second
memory limit per test:256 megabytes
inputstandard:standard input
outputstandard: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 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]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.
Sample Input
5
1
5
3
8
2
Sample Output
4
题面描述:
上面的代码是Bessie写的冒泡排序,code中的“moo”命令可以理解为打印一句moo,现在要计算对于给出的数据若是按照Bessie的代码会打印几句“moo”。
题目分析:
这是一道思维题,看数据最大是1e5,如果直接照抄Bessie的代码基础上每次从1到n枚举是会超时的,这时候就要想其他的方法算。根据冒泡排序的原理,每次找一个最大的数放到后面,其他的数被动前移或不变。如:
0 2 9 3 8 5 4 7(对此数列进行冒泡排序)会变成
0 2 3 8 5 4 7 9(此时 3 6 5 4 7 各向前移动了一位)
0 2 3 5 4 7 8 9(此时 5 4 7 各向前移动了一位)
0 2 3 4 5 7 8 9(此时 4 向前移动了一位)
观察可以发现冒泡排序的次数就是向前移动位数最多的那个数字也就是 3 ,而“moo”的次数是 3+1=4 次,即是答案。
代码:
#include<algorithm>
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
#include<vector>
using namespace std;
long long ans=-1,i,n;
struct num{
long long num,pos;
}a[100005];
bool cmp(num a,num b){
if(a.num!=b.num) return a.num<b.num;
else return a.pos<b.pos;
}
int main(){
cin>>n;
for(i=1;i<=n;i++) cin>>a[i].num,a[i].pos=i;
sort(a+1,a+1+n,cmp);
for(i=1;i<=n;i++) ans=max(ans,a[i].pos-i+1);
cout<<ans;
}