1
0

CodeForces-1408E.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct DSU {
  4. vector<int> parent, size;
  5. explicit DSU(int n) : parent(n), size(n, 1) { iota(parent.begin(), parent.end(), 0); }
  6. int find(int x) { return parent[x] == x ? x : parent[x] = find(parent[x]); }
  7. bool unite(int a, int b) {
  8. a = find(a); b = find(b);
  9. if (a == b) return false;
  10. if (size[a] < size[b]) swap(a, b);
  11. parent[b] = a; size[a] += size[b];
  12. return true;
  13. }
  14. };
  15. struct Edge { int u, v; long long weight; };
  16. int main() {
  17. ios::sync_with_stdio(false);
  18. cin.tie(nullptr);
  19. int sets, values;
  20. cin >> sets >> values;
  21. vector<long long> a(sets), b(values);
  22. for (long long &x : a) cin >> x;
  23. for (long long &x : b) cin >> x;
  24. vector<Edge> edges;
  25. long long total = 0;
  26. for (int i = 0; i < sets; ++i) {
  27. int size;
  28. cin >> size;
  29. while (size--) {
  30. int value;
  31. cin >> value;
  32. --value;
  33. long long weight = a[i] + b[value];
  34. edges.push_back({i, sets + value, weight});
  35. total += weight;
  36. }
  37. }
  38. sort(edges.begin(), edges.end(), [](const Edge &x, const Edge &y) {
  39. return x.weight > y.weight;
  40. });
  41. DSU dsu(sets + values);
  42. long long kept = 0;
  43. for (const Edge &edge : edges) {
  44. if (dsu.unite(edge.u, edge.v)) kept += edge.weight;
  45. }
  46. cout << total - kept << '\n';
  47. return 0;
  48. }