CodeForces 689 D Friends and Subsequences
题解:
如果左端点来说, 那么对于a[i]来说是向上的一条折线, b[i]来说是向下的一条折线, 那么如果这2个折线求交点个数的话, 我们可以二分去求第一个 a[i] == b[i] 的地方, 求最后一个a[i] == b[i]的地方。
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<bits/stdc++.h> using namespace std; #define Fopen freopen("_in.txt","r",stdin); freopen("_out.txt","w",stdout); #define LL long long #define ULL unsigned LL #define fi first #define se second #define pb push_back #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define lch(x) tr[x].son[0] #define rch(x) tr[x].son[1] #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) typedef pair<int,int> pll; const int inf = 0x3f3f3f3f; const int _inf = 0xc0c0c0c0; const LL INF = 0x3f3f3f3f3f3f3f3f; const LL _INF = 0xc0c0c0c0c0c0c0c0; const LL mod = (int)1e9+7; const int N = 2e5 + 100; int a[N], b[N]; int Log[N]; int Max[N][20]; int Min[N][20]; void init(int n) { for(int i = -(Log[0]=-1); i < N; i++) Log[i] = Log[i - 1] + ((i & (i - 1)) == 0); for(int i = 1; i <= n; ++i) Max[i][0] = a[i], Min[i][0] = b[i]; for(int j = 1; j <= Log[n]; j++) for(int i = 1; i+(1<<j)-1 <= n; i++) Max[i][j] = max(Max[i][j-1], Max[i+(1<<(j-1))][j-1]), Min[i][j] = min(Min[i][j-1], Min[i+(1<<(j-1))][j-1]); } int QMin(int l, int r) { int k = Log[r - l + 1]; return min(Min[l][k], Min[r-(1<<k)+1][k]); } int QMax(int l, int r){ int k = Log[r - l + 1]; return max(Max[l][k], Max[r-(1<<k)+1][k]); } int main(){ int n; scanf("%d", &n); for(int i = 1; i <= n; ++i) scanf("%d", &a[i]); for(int i = 1; i <= n; ++i) scanf("%d", &b[i]); init(n); LL ans = 0; for(int i = 1; i <= n; ++i){ int l = i, r = n; while(l <= r){ int m = l+r >> 1; if(QMin(i, m) > QMax(i, m)) l = m + 1; else r = m - 1; } if(QMin(i, l) != QMax(i, l)) continue; int tl = l; l = i, r = n; while(l <= r){ int m = l+r >> 1; if(QMin(i, m) >= QMax(i, m)) l = m + 1; else r = m - 1; } ans += l - tl; } cout << ans << endl; return 0; }