题目链接
Description
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. ……………………
题意:
FJ有n头牛,现在它们排成一排,每一头牛都有一个不同的编号(1-n),现在知道从第二头牛开始每头牛左边比自己编号小的牛的数目,让你确定每头牛的编号。
思路:
我用一个树状数组来表示第i头牛的左边有多少比自己标号小的,树状数组必须初始化,每个节点必须加1。每次我们可以知道最后一头牛的编号x,然后然后更新x以后的区间使其都减1(这里也可以使用线段树,不过感觉比较麻烦,因为树状数组的特性,只需要更新x就好了),然后求倒数第二头的编号,我们只需要找到一个x,使得sum(x) 为该牛左边小于其编号牛的数量,使用二分查找可以提高查找速率,然后是倒数第三头的………………………………
因为是倒着来的,为了熟悉stl,我使用了其封装的stack 栈。
下面是解题代码:
线段树的方法我就暂时不写了,有感兴趣的可以上网搜一下其他人的代码,都比我写的好啊!!