Lost Cows(树状数组+二分)

来源:互联网 发布:python 自动完成 编辑:程序博客网 时间:2024/06/10 11:57
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.
Input
* 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.
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

题目链接:http://poj.org/problem?id=2182

分析:由给定的数据我们从后往前进行求解s[n],s[n]...s[1]
当我们求解s[k]的时候,由于s[k+1]...s[n]已求到,所以只要确定了s[k]
就能确定s[k+1]~s[n]中比s[k]小的个数num,从而k-1-num就是s[k]前面比s[k]小的个数
如果s[k]-1-num == a[k](既输入的值),则该点可以是s[k],而如何确定s[k]呢?在这可以用二分来确定s[k]
如何确定num呢?在这用树状数组来求num
二分时:
如果s[k]-1-num>=a[k]则right=mid,表示s[k]可以继续变小
否则left=mid+1,表示s[k]必须变大才可能满足
注意到这里的s[k]-1-num>=a[k]则right=mid,为什么不直接s[k]-1-num == a[k]时直接得到s[k]呢?

#include<stdio.h>#include<string.h>#define Max 8005int tree[Max];int input[Max];int ans[Max];int n;int lowbit(int x){    return x & (-x);}void modify(int x,int add)//一维{      while(x<=n)      {              tree[x]+=add;            x+=lowbit(x);     }}int query(int x)//求1到x之间的和{      int ret=0;     while(x!=0)      {               ret+=tree[x];           x-=lowbit(x);       }      return ret;}int find(int left,int right,int x){int mid,num,key;while(left<=right){mid=(left+right)/2;num=query(mid);if(mid-1-num>=x){key=mid;right=mid-1;}else left=mid+1;}return key;}int main(){freopen("b.txt","r",stdin);while(scanf("%d",&n)==1){memset(input,0,sizeof(input));int i,k;for(i=2;i<=n;i++)scanf("%d",&input[i]);for(i=n;i>=1;i--){k=find(1,n,input[i]);ans[i]=k;modify(k,1);}for(i=1;i<=n;i++){printf("%d",ans[i]);printf("\n");}}return 0;}


0 0