結果

問題 No.1036 Make One With GCD 2
ユーザー potoooooooo
提出日時 2020-04-25 21:45:56
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 1,122 ms / 2,000 ms
コード長 1,658 bytes
コンパイル時間 2,463 ms
コンパイル使用メモリ 206,340 KB
最終ジャッジ日時 2025-01-10 01:41:21
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

template<class T> struct SparseTable {
    vector<vector<T>> dat;
    vector<int> lookup;
    using Func = function<T(T a, T b)>;
    Func f; T e;
    SparseTable(Func f, T e) : f(f), e(e) {}
    SparseTable(const vector<T> &v, Func f, T e) : f(f), e(e) { build(v); }
    void build(const vector<T> &v) {
        int sz = v.size(), b = 0;
        while ((1 << b) <= sz) b++;
        int n = 1 << b;
        dat.assign(b, vector<T>(n, e));
        for (int i = 0; i < n; i++) dat[0][i] = v[i];
        for (int i = 1; i < b; i++) {
            int d = 1 << i;
            for (int j = 0; j + d <= n; j++) {
                dat[i][j] = f(dat[i-1][j], dat[i-1][j+d/2]);
            }
        }
        lookup.resize(n+1, 0);
        for (int i = 2; i <= n; i++) {
            lookup[i] = lookup[i/2] + 1; 
        }
    }
    // query : [l, r)
    T query(int l, int r) {
        int b = lookup[r - l];
        return f(dat[b][l], dat[b][r-(1<<b)]);
    }
};

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n; cin >> n;
    using D = long long;
    function<D(D, D)> g = [&](D a, D b) {
        if (b == 0LL) return a;
        if (a % b) return g(b, a % b);
        return b;
    };
    vector<D> a(n);
    for (auto &x: a) cin >> x;
    a.emplace_back(1);
    SparseTable<long long> st(a, g, 0);
    long long ans = 0;
    int rg = 1;
    for (int i = 0; i < n; i++) {
        long long curr = st.query(i, rg);
        while (curr != 1 && rg < n) curr = g(curr, a[rg++]);
        ans += n - rg + (curr == 1);
        if (i+1 == rg) rg++;
    }
    cout << ans << "\n";
    return 0;
}
0