結果

問題 No.1036 Make One With GCD 2
ユーザー hedwig100
提出日時 2020-04-25 22:31:05
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 1,149 ms / 2,000 ms
コード長 1,728 bytes
コンパイル時間 1,689 ms
コンパイル使用メモリ 174,380 KB
実行使用メモリ 19,280 KB
最終ジャッジ日時 2024-09-16 14:02:15
合計ジャッジ時間 21,674 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); i ++)
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PL;
typedef pair<int,int> P;
const ll INF = 1e9;
const ll MOD = 1e9 + 7;

template <class T> class SegmentTree {
    int N = 1;
    vector<T> tree;
    function<T(T,T)> func;
    T unit;
    
    public:

    SegmentTree(vector<T> array,function<T(T,T)> _func,T _unit) :func(_func),unit(_unit) {
        int n = array.size();
        while (N < n) N *= 2;
        tree = vector<T>(2*N,unit);

        for (int i = 0;i < n; i++) tree[i + N - 1] = array[i];
        for (int i = N - 2; i >= 0; i--) tree[i] = func(tree[2*i + 1],tree[2*i + 2]);  
    }

    void update(int k,T x) {//k番目の要素をxに変更する
        k += N - 1;
        tree[k] = x;
        while (k) {
            k = (k - 1)/2;
            tree[k] = func(tree[2*k + 1],tree[2*k + 2]);
        }
    }

    T query(int l,int r) {//開区間[l,r)のクエリに答える
        if (r <= l) return unit;

        l += N - 1;
        r += N - 2;
        T ans = unit;

        while (r - l > 1) {
            if ((l&1) == 0) ans = func(ans,tree[l]);
            if ((r&1) == 1) {ans = func(ans,tree[r]); r--;}
            l /= 2;
            r = (r - 1)/2;
        }

        if (l == r) ans = func(ans,tree[l]);
        else ans = func(func(ans,tree[l]),tree[r]);
        return ans;
    }
};

int main() {
    int n; cin >> n;
    vector<ll> a(n);
    rep(i,n) cin >> a[i];
    
    SegmentTree<ll> st(a,[](ll a, ll b){return __gcd(a,b);},0);

    int r = 0;
    ll ans = 0;
    for (int l = 0;l < n;l ++) {
        while (r < n && st.query(l,r + 1) != 1) r ++;
        ans += n - r;
    }
    cout << ans << endl;
}
0