Out of Sorts

16 篇文章 0 订阅
10 篇文章 0 订阅

传送门

题面:

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yjonben

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值