【并查集分块】Codeforces 475D CGCDSSQ

来源:互联网 发布:2017年网络新项目 编辑:程序博客网 时间:2024/06/12 00:41

题目点这里


bin神说这题和他当年出的一道题差不多TAT

听了半天终于听懂了TAT。。。

利用gcd的递减性 从左往右把一段的gcd和最新的数相同的的放到一个并查集里去。。

可以证明段数是不会增加的 = =


#include <cstdio>#include <iostream>#include <map>using namespace std;const int Nmax = 1e5 + 5;int N, Q;int a[Nmax], f[Nmax], g[Nmax];map <int, long long> m;int find(int x) { return (x == f[x]) ? x : f[x] = find(f[x]); }inline void Union(int u, int v) { f[find(u)] = find(v); }inline int gcd(int a, int b){    if (!b) return a;    for (int t = a % b; t; a = b, b = t, t = a % b);    return b;}int main(){    ios :: sync_with_stdio(false);    cin >> N;    for (int i = 1; i <= N; ++ i) cin >> a[i];    for (int i = 1; i <= N + 1; ++ i) f[i] = i;        for (int i = N; i; -- i) {        int s = i, last = i;        g[i] = a[i];        for (int j = find(i + 1); j <= N; j = find(j + 1)) {            g[j] = gcd(a[i], g[j]);            if (g[j] ^ g[last]) {                m[g[last]] += last - s + 1;                s = last + 1;            }            else Union(last, j);            last = j;        }        m[g[N]] += N - s + 1;    }        for (cin >> Q; Q --; ) {        int x; cin >> x;        cout << m[x] << endl;    }        return 0;}


0 0