Lost Cows Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 8838 Accepted: 5657
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, NOutput
* 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
USACO 2003 U S Open Orange#include這道題還可以用數組數組做,換一種思路,明天再做,(未完待續。。)#define N 8002 int num[N],ans[N]; struct segment { int l,r,len; }s[N]; void build(int root,int l,int r)//建立樹 { s[root].l=l; s[root].r=r; s[root].len=r-l+1;//線段的區間(按照題意) if(l==r)return; build(2*root,l,(l+r)/2); build(2*root+1,(l+r)/2+1,r); } int query(int root,int k)//查找線段樹 { s[root].len--;//每查找一次,區間就減1,說明找到了一個編號,就刪除那個節點; if(s[root].l==s[root].r) return s[root].l;//說明找到葉子節點 else if(k<=s[2*root].len) {return query(2*root,k);}//遞歸左子樹 else {return query(2*root+1,k-s[2*root].len);}//遞歸右子樹 } int main() { int n; scanf("%d",&n); for(int i=2;i<=n;i++) scanf("%d",&num[i]); num[1]=0;//第一個編號為0; build(1,1,n); for(int i=n;i>=1;i--)//倒序 ans[i]=query(1,num[i]+1); for(int i=1;i<=n;i++) printf("%d\n",ans[i]); return 0; }