51Nod 1272最大距离 (树状数组维护前缀最小值)

题目链接 最大距离

其实主流解法应该是单调栈……我用了树状数组。

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 #define rep(i, a, b)    for (int i(a); i <= (b); ++i)
 6 
 7 const int N = 100010;
 8 
 9 struct node{
10     int x, y;
11     friend bool operator < (const node &a, const node &b){
12         return a.x == b.x ? a.y < b.y : a.x < b.x; 
13     }
14         //sort细节,初始ID在前的最后也要在前
15 } a[N];
16 
17 int f[N];
18 int n, ans;
19 
20 void update(int x, int val){
21     for (; x <= n; x += x & -x) f[x] = min(f[x], val);
22 }
23 
24 //树状数组更新
25 
26 int query(int x){
27     int ret = 1 << 30;
28     for (; x; x -= x & -x) ret = min(ret, f[x]);
29     return ret;
30 }
31 
32 //树状数组查询前缀最小值
33 
34 int main(){
35 
36     scanf("%d", &n);
37     rep(i, 1, n){
38         scanf("%d", &a[i].x);
39         a[i].y = i;
40     }
41 
42     sort(a + 1, a + n + 1);
43     rep(i, 0, n + 100) f[i] = 1 << 30; //Init...
44 
45     ans = -1;
46     rep(i, 1, n){
47         update(a[i].y, a[i].y);
48         int cnt = query(a[i].y);
49         ans = max(ans, a[i].y - cnt);
50     }
51     printf("%d
", ans);
52     return 0;
53 }
原文地址:https://www.cnblogs.com/cxhscst2/p/6675273.html