/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 4ms 320.0 KiB
#2 Accepted 13ms 320.0 KiB
#3 Time Exceeded ≥1088ms ≥596.0 KiB
#4 Accepted 735ms 680.0 KiB
#5 Accepted 660ms 596.0 KiB
#6 Time Exceeded ≥1083ms ≥592.0 KiB

Code

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

#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);
using ll = long long;

struct DSU {
  vector<int> par, sz;
  int N;

  DSU() {}
  DSU(int N) : N(N) {
    sz.resize(N);
    fill(sz.begin(), sz.end(), 1);

    par.resize(N);
    iota(par.begin(), par.end(), 0);
  }

  void union_sets(int u, int v) {
    u = get_parent(u);
    v = get_parent(v);
    if (u == v) return;
    
    if (sz[u] < sz[v]) swap(u, v);
    par[v] = u;
    sz[u] += sz[v];
  }

  bool in_same_set(int u, int v) {
    return (get_parent(u) == get_parent(v));
  }

  int get_parent(int u) {
    if (u == par[u]) return u;
    par[u] = get_parent(par[u]);
    return par[u];
  }

  int get_size(int u) {
    return sz[get_parent(u)];
  }
};

int main() {
  FAST;
  
  int tc = 1, ti;
  cin >> tc;

  for (ti = 1; ti <= tc; ++ti) {
    ll n, k, i, j, x, curr, ans;
    cin >> n >> k;

    vector<ll> a(n);
    for (i = 0; i < n; ++i) cin >> a[i];

    DSU dsu(n);

    for (x = 2; x <= 32000; ++x) {
      j = -1;
      for (i = 0; i < n; ++i) {
        if (a[i] % x == 0) {
          if (j == -1) j = i;
            else dsu.union_sets(j, i);
        }
      }
    }

    vector<ll> col(n);
    for (i = 0; i < n; ++i) col[i] = dsu.get_parent(i);

    vector<vector<ll>> pf(n, vector<ll>(1, 0));
    for (i = 0; i < n; ++i) {
      pf[col[i]].push_back(a[i]);
    }
    for (i = 0; i < n; ++i) {
      sort(pf[i].begin()+1, pf[i].end());
      reverse(pf[i].begin()+1, pf[i].end());
      for (j = 1; j < (int)pf[i].size(); ++j) {
        pf[i][j] += pf[i][j-1];
      }
    }

    vector<ll> ptr(n, 0);
    curr = 0;

    auto add = [&](ll col) {
      curr -= pf[col][ptr[col]];
      ptr[col] += 1;
      curr += pf[col][ptr[col]];
    };

    auto remove = [&](ll col) {
      curr -= pf[col][ptr[col]];
      ptr[col] -= 1;
      curr += pf[col][ptr[col]];
    };

    for (i = 0; i < k; ++i) add(col[i]);
    ans = curr;

    for (i = k; i < n; ++i) {
      remove(col[i-k]);
      add(col[i]);
      ans = max(ans, curr);
    }

    cout << ans << "\n";
  }

  return 0;
}

Information

Submit By
Type
Submission
Problem
P1063 Another Maximum Sum in Subarray
Language
C++17 (G++ 13.2.0)
Submit At
2024-10-04 08:47:13
Judged At
2024-11-11 02:43:21
Judged By
Score
25
Total Time
≥1088ms
Peak Memory
≥680.0 KiB