题目链接:
http://codeforces.com/problemset/problem/91/B
题意:
给你一个数列,让你找到最右边比这个数小的数的位置,如果没有就输出-1
题解:
线段树中二分,查询最小值,然后二分区间就好了
代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 #define MS(a) memset(a,0,sizeof(a)) 5 #define MP make_pair 6 #define PB push_back 7 const int INF = 0x3f3f3f3f; 8 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL; 9 inline ll read(){ 10 ll x=0,f=1;char ch=getchar(); 11 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 12 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} 13 return x*f; 14 } 15 ////////////////////////////////////////////////////////////////////////// 16 const int maxn = 1e5+10; 17 18 int a[maxn],tree[maxn<<2],ans[maxn],cnt; 19 20 void pushup(int rt){ 21 tree[rt] = min(tree[rt<<1],tree[rt<<1|1]); 22 } 23 24 void build(int rt,int l,int r){ 25 tree[rt] = INF; 26 if(l == r){ 27 tree[rt] = a[l]; 28 return ; 29 } 30 31 int mid = (l+r)/2; 32 build(rt<<1,l,mid); 33 build(rt<<1|1,mid+1,r); 34 pushup(rt); 35 } 36 37 void query(int rt,int l,int r,int x){ 38 if(l == r){ 39 ans[++cnt] = l-x-1; 40 return ; 41 } 42 43 int mid = (l+r)/2; 44 if(tree[rt<<1|1] < a[x]) 45 query(rt<<1|1,mid+1,r,x); 46 else 47 query(rt<<1,l,mid,x); 48 } 49 50 void update(int rt,int l,int r,int x){ 51 if(l == r){ 52 tree[rt] = INF; 53 return ; 54 } 55 56 int mid = (l+r)/2; 57 if(x>mid) 58 update(rt<<1|1,mid+1,r,x); 59 else 60 update(rt<<1,l,mid,x); 61 pushup(rt); 62 } 63 64 int main(){ 65 int n = read(); 66 for(int i=1; i<=n; i++) 67 a[i] = read(); 68 build(1,1,n); 69 70 for(int i=1; i<=n; i++){ 71 if(tree[1] >= a[i]) 72 ans[++cnt] = -1; 73 else 74 query(1,1,n,i); 75 update(1,1,n,i); 76 } 77 78 for(int i=1; i<=cnt; i++) 79 cout << ans[i] << " "; 80 cout << endl; 81 82 return 0; 83 } 84 // http://codeforces.com/problemset/problem/91/B