Lost Cows 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. Input * Line 1: A single integer, N Output * 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. Sample Input 5 1 2 1 0 Sample Output 2 4 5 3 1 Source |
Time Limit: 1000MS |
| Memory Limit: 65536K |
Total Submissions: 8004 |
| Accepted: 5100 |
评测链接:http://poj.org/problem?id=2182
解法:
在网上看的题解,不得不说,又了解了线段树的一种应用方法。
我们可以假想一个1到n的序列x,表示1到n头牛的编号。
第n头牛在序列x中,只有a[n]头牛的编号比它小,那么它在序列中的就排在第a[n]+1位,也即第n头牛的编号为a[n]+1,用d[n]=a[n]+1记录编号。
第n-1头牛对应的编号在序列中就是排在第a[n-1]+1个点所对应的编号(不包括d[n]号点)。
。。。。。。
以样例为例:
x:1 2 3 4 5
a:0 1 2 1 0
第一步:a[n]=0,在序列x中排在第0+1位,所以d[n]=1;
第二步:不算d[n]号点,新x序列为:2 3 4 5
a[n-1]=1,在序列中排在第1+1位,即d[n-1]=3;
。。。。。。
具体做法:用线段树sum[]维护序列x的区间中p【pl,pr】中,有多少个已被确认的点,那么新序列x在区间p中就有pr-pl+1-sum[p]个点。在查找新序列中第i位时,就可以用线段树进行查找。(鄙人词乏,查找过程真不知该咋样叙述,还请看代码上的注解。)
代码: