1597 Lost Cows 解题报告

本文解析了一道名为LostCows的编程题,该题要求根据每个奶牛前面较小品牌数量的数据,还原奶牛的品牌排列顺序。文章提供了两种解题思路及代码实现,一种是基于遍历的方法,另一种则利用了线段树结构进行优化。

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

  

Lost Cows

时间限制(普通/Java):1000MS/10000MS     运行内存限制:65536KByte
总提交: 3            测试通过: 3

描述

N (2 <= N <= 8,000) cows have unique brands in the range 1..N. In a spectacular display of poor judgment, they visited the neighborhood 'watering hole' and drank a few too many beers before dinner. When it was time to line up for their evening meal, they did not line up in the required ascending numerical order of their brands.

Regrettably, FJ does not have a way to sort them. Furthermore, he's not very good at observing problems. Instead of writing down each cow's brand, he determined a rather silly statistic: For each cow in line, he knows the number of cows that precede that cow in line that do, in fact, have smaller brands than that cow.

Given this data, tell FJ the exact ordering of the cows.

输入

* Line 1: A single integer, N

* Lines 2..N: These N-1 lines describe the number of cows that precede a given cow in line and have brands smaller than that cow. Of course, no cows precede the first cow in line, so she is not listed. Line 2 of the input describes the number of preceding cows whose brands are smaller than the cow in slot #2; line 3 describes the number of preceding cows whose brands are smaller than the cow in slot #3; and so on.

输出

* Lines 1..N: Each of the N lines of output tells the brand of a cow in line. Line #1 of the output tells the brand of the first cow in line; line 2 tells the brand of the second cow; and so on.

 

样例输入

 

5
1
2
1
0

 

样例输出

 

2
4
5
3
1
 好久没写解题报告了,可能自己觉得实力不行,写这个可能会误人子弟,不管了,留给自己以后看,大家就参考吧。
分析:
题目输入数据里列出除第一个以外其他数的前面比他小的个数。想想要求出他是数字多少,这个只要他前面比他小的个数+他下面的比他小的数个数+1就是答案了。
思路简单吧,其实这个题目是简单题。
我这边说说如何去找他下面的比他小的数的个数,首先对最后一个输入的数分析,后面已经没有数了,那么他的前面的比他小的个数+1就是答案。
然后看前面的数字,前面数字+(往后搜有小于他的数字就对当前数字+1搜到最后为止返回个数)+1就是答案。
第一个数就用排除就可以。
有点乱啊,看例子直接:
假如原来数列是
2 6 1 3 4 5
那么我输入时候
6
1
0
2
3
4
按照刚才的描述,我们先开个 空间来保存输入的数a[8001],zhan[8001]保存原来的数;
a[0]=4+1;这个毫无疑问吧,
往上就是
大家结合代码吧,还是容易看懂的:
学了线段树终于提高效率了,不过思路不是自己的,惭愧:
解题思路:对于一个给定序列,从后面往前面看是前面有几个数字是比他小的, 
0代表前面没有数字比他小,所以肯定是1,把1去掉。
1代表剩下的数中他排在第2位,剩下2,3,4,5,所以是3,
2代表剩下的数中他排在第3位,剩下2,4,5,所以是5,
1代表剩下的数中他排在第2位,剩下2,4,所以是4 ,剩下了一个2。
    搜索排在第n位的数是几时可用线段树实现,对于一个线段树中的所代表的线段[a,b],结点中的数值纪录[a,b]中还有多少人没有被去掉,记为len,所以对于一个在剩余数字队列中排在第n位,看这个人是在一个结点的左子树中还是右子树中,
判断的依据是用左子树了的r和n比较,
如果len>n说明在左子树形成的队列中有足够的数字使他排在第n位,于是递归找左子树。
如果len <n说明在左子树形成的队列中没有足够的数字使他排在第n位,所以他在右子树的第n-len位
于是递归在右子树中找;
当然每找到一个数字,要将所有的祖先结点信息改变,即len--;
代码:
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

helihui123

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

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

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

打赏作者

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

抵扣说明:

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

余额充值