/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 2ms 328.0 KiB
#2 Accepted 3ms 484.0 KiB
#3 Accepted 195ms 688.0 KiB
#4 Accepted 148ms 608.0 KiB
#5 Accepted 247ms 644.0 KiB
#6 Accepted 62ms 576.0 KiB
#7 Accepted 69ms 584.0 KiB
#8 Accepted 101ms 604.0 KiB
#9 Accepted 120ms 596.0 KiB
#10 Accepted 36ms 596.0 KiB
#11 Accepted 18ms 568.0 KiB
#12 Time Exceeded ≥1025ms ≥716.0 KiB
#13 Time Exceeded ≥1029ms ≥536.0 KiB

Code

#include <bits/stdc++.h>

#pragma GCC optimize("Ofast")
using namespace std;

class DSU {
public:
  DSU(int n) : Par(n), rank(n, 0), siz(n, 1) {
    for (int i = 0; i < n; ++i) {
      Par[i] = i;
    }
  }

  int Leader(int x) {
    if (Par[x] != x) {
      Par[x] = Leader(Par[x]);
    }
    return Par[x];
  }

  bool unite(int x, int y) {
    int X = Leader(x);
    int Y = Leader(y);

    if (X != Y) {
      if (rank[X] > rank[Y]) {
        Par[Y] = X;
        siz[X] += siz[Y];
      } else if (rank[X] < rank[Y]) {
        Par[X] = Y;
        siz[Y] += siz[X];
      } else {
        Par[Y] = X;
        siz[X] += siz[Y];
        ++rank[X];
      }
      return true;
    }
    return false;
  }
  int size(int x) {
    int root = Leader(x);
    return siz[root];
  }

private:
  vector<int> Par;
  vector<int> rank;
  vector<int> siz;
};

void solve(int cs) {
  int n, k;
  cin >> n >> k;
  vector<int> a(n);
  for (int i = 0; i < n; i++) {
    cin >> a[i];
  }
  DSU dsu(n + 1);
  for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
      if (__gcd(a[i], a[j]) > 1) {
        dsu.unite(i, j);
      }
    }
  }

  map<int, vector<int>> g;
  for (int i = 0; i < n; i++) {
    g[dsu.Leader(i)].push_back(i);
  }
  map<int, vector<int>> who;
  for (auto &[L, group] : g) {
    for (auto id : group) {
      who[L].push_back(a[id]);
    }
    sort(who[L].rbegin(), who[L].rend());
  }

  int64_t res = 0;
  for (int i = 0; i <= n - k; i++) {
    int64_t sum = 0;
    for (auto &[L, group] : g) {
      int j = 0;
      for (auto &id : group) {
        if (id >= i && id < i + k) {
          sum += who[L][j++];
        }
      }
    }
    res = max(res, sum);
  }
  cout << res << "\n";
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int tc = 1;
  cin >> tc;
  for (int cs = 1; cs <= tc; cs++) {
    solve(cs);
  }
  return 0;
}

Information

Submit By
Type
Submission
Problem
P1063 Another Maximum Sum in Subarray
Language
C++20 (G++ 13.2.0)
Submit At
2024-07-15 06:51:58
Judged At
2024-11-11 03:21:50
Judged By
Score
65
Total Time
≥1029ms
Peak Memory
≥716.0 KiB