码迷,mamicode.com
首页 > 其他好文 > 详细

Codeforces Round #361 (Div. 2) D. Friends and Subsequences RMQ+二分

时间:2016-09-26 21:44:46      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

题目链接

http://codeforces.com/problemset/problem/689/D

代码

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 using namespace std;
 5 
 6 const int maxn = 200000 + 10;
 7 int n, a[maxn], b[maxn];
 8 int d_min[maxn][30];
 9 int d_max[maxn][30];
10 
11 void RMQ_init() {
12     for (int i = 0; i<n; i++) d_max[i][0] = a[i], d_min[i][0] = b[i];
13     for (int j = 1; (1 << j) <= n; j++)
14         for (int i = 0; i + (1 << j) - 1 < n; i++) {
15             d_min[i][j] = min(d_min[i][j - 1], d_min[i + (1 << (j - 1))][j - 1]);
16             d_max[i][j] = max(d_max[i][j - 1], d_max[i + (1 << (j - 1))][j - 1]);
17         }
18 }
19 
20 int RMQ_min(int L, int R) {
21     int k = 0;
22     while ((1 << (k + 1)) <= R - L + 1) k++;
23     return min(d_min[L][k], d_min[R - (1 << k) + 1][k]);
24 }
25 
26 int RMQ_max(int L, int R) {
27     int k = 0;
28     while ((1 << (k + 1)) <= R - L + 1) k++;
29     return max(d_max[L][k], d_max[R - (1 << k) + 1][k]);
30 }
31 
32 int main()
33 {
34     cin >> n;
35     for (int i = 0; i < n; i++) scanf("%d", &a[i]);
36     for (int i = 0; i < n; i++) scanf("%d", &b[i]);
37     RMQ_init();
38     long long ans = 0;
39     for (int i = 0; i < n; i++) {
40         if (a[i] > b[i]) continue;
41         int first_r = -1, last_r = -1;
42         int l = i, r = n - 1, mid;
43 
44         while (l <= r) {
45             mid = (l + r) / 2;
46             if (RMQ_max(i, mid) == RMQ_min(i, mid)) first_r = mid;
47             if (RMQ_max(i, mid) >= RMQ_min(i, mid)) r = mid - 1;
48             else l = mid + 1;
49         }
50         if (first_r == -1) continue;
51 
52         l = i; r = n - 1;
53         while (l <= r) {
54             mid = (l + r) / 2;
55             if (RMQ_max(i, mid) > RMQ_min(i, mid))
56                 r = mid - 1;
57             else l = mid + 1, last_r = mid;
58         }
59 
60         ans += last_r - first_r + 1;
61     }
62     cout << ans << endl;
63     return 0;
64 }

 

Codeforces Round #361 (Div. 2) D. Friends and Subsequences RMQ+二分

标签:

原文地址:http://www.cnblogs.com/baocong/p/5910568.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!