1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #include <iostream> #include <vector> #define maxn 1000010 #define ll long long using namespace std;
int n; ll a[maxn];
ll ans; int suf[maxn], sn[61], sm[61]; vector<pair<int, int>> A[maxn], B[maxn]; void solve(int l, int r) { if (l == r) return ++ans, void(); int m = l + r >> 1; solve(l, m); solve(m + 1, r); ll mn = 1e18, mx = 0, Min = 1e18, Max = 0; for (int i = m + 1; i <= r; ++i) A[i].clear(), B[i].clear(); for (int i = m + 1; i <= r; ++i) { mn = min(mn, a[i]); mx = max(mx, a[i]); suf[i] = __builtin_popcountll(mn) == __builtin_popcountll(mx); } suf[r + 1] = 0; for (int i = r; i >= m; --i) suf[i] += suf[i + 1]; mn = 1e18; mx = 0; for (int i = m, pn = m, pm = m, cm, cn; i >= l; --i) { mn = min(mn, a[i]); cn = __builtin_popcountll(mn); mx = max(mx, a[i]); cm = __builtin_popcountll(mx); while (pn < r && min(Min, a[pn + 1]) >= mn) Min = min(Min, a[++pn]); while (pm < r && max(Max, a[pm + 1]) <= mx) Max = max(Max, a[++pm]); if (cn == cm) ans += min(pn, pm) - m; if (pn < pm) A[pn].emplace_back(cm, -1), A[pm].emplace_back(cm, 1); else if (pm < pn) B[pm].emplace_back(cn, -1), B[pn].emplace_back(cn, 1); ans += suf[max(pn, pm) + 1]; } mn = 1e18; mx = 0; for (int i = 0; i <= 60; ++i) sm[i] = sn[i] = 0; for (int i = m + 1; i <= r; ++i) { mn = min(mn, a[i]); mx = max(mx, a[i]); sn[__builtin_popcountll(mn)]++; sm[__builtin_popcountll(mx)]++; for (auto [k, opt] : A[i]) ans += opt * sn[k]; for (auto [k, opt] : B[i]) ans += opt * sm[k]; } }
int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i]; solve(1, n); cout << ans << "\n"; return 0; }
|