[Usaco2003 Open]Lost Cows题解
Background
Special for beginners, ^_^
Description
N (2 <= N <= 8,000) cows have unique brands in the range 1..N. In a spectacular display of poor judg ment, they visited the neighborhood 'watering hole' and drank a few too many beers before dinner. Wh en it was time to line up for their evening meal, they did not line up in the required ascending num erical 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 s illy 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 c ows.
1~n,乱序排列,告诉每个位置的前面的数字中比它小的数的个数,求每个位置的数字是多少
Format
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 i n slot #2; line 3 describes the number of preceding cows whose brands are smaller than the cow in sl ot #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.
Samples
输入数据 1
5
1
2
1
0
输出数据 1
2
4
5
3
1
Limitation
1s, 1024KiB for each test case.
思路
线段树。
代码见下
#include<bits/stdc++.h>
using namespace std;
int n,m,a[5000006],aa[5000006],a2[5000006],u,x,y;
int lb(int x){
return x&(-x);
}
void ci(int x,int d){
while(x<=n){
a2[x]+=d;
x+=lb(x);
}
}
int co(int x){
int lks=0;
while(x>=1){
lks+=a2[x];
x-=lb(x);
}
return lks;
}
int main(){
ios::sync_with_stdio (false);
scanf("%d",&n);
for(int i=2;i<=n;i++){
scanf("%d",&a[i]);
}
for(int i=1;i<=n;i++){
ci(i,1);
}
for(int i=n;i>=1;i--){
int l=1,r=n,md=0;
while(l<=r){
int mid=(l+r)/2;
if(co(mid-1)<=a[i]){
md=mid;
l=mid+1;
}
else{
r=mid-1;
}
}
ci(md,-1);
aa[i]=md;
}
for(int i=1;i<=n;i++){
cout<<aa[i]<<"\n";
}
return 0;
}

浙公网安备 33010602011771号