pls solve the optimize correct code for prblm in c...
作成日: 2026年5月16日
使用モデル GPT-5.5 Thinking by Chat01
作成日: 2026年5月16日
使用モデル GPT-5.5 Thinking by Chat01
pls solve the optimize correct code for prblm in c++.
Paste this in the editor. It uses DSU / Union-Find: sort edges by weight, keep joining nodes, and the first weight that connects source to destination is the minimum possible stress.
cpp#include <bits/stdc++.h> using namespace std; class DSU { public: vector<int> parent, rankv; DSU(int n) { parent.resize(n + 1); rankv.assign(n + 1, 0); for (int i = 1; i <= n; i++) parent[i] = i; } int find(int x) { if (parent[x] == x) return x; return parent[x] = find(parent[x]); } void unite(int a, int b) { a = find(a); b = find(b); if (a == b) return; if (rankv[a] < rankv[b]) { parent[a] = b; } else if (rankv[a] > rankv[b]) { parent[b] = a; } else { parent[b] = a; rankv[a]++; } } }; int getMinimumStress( int graph_nodes, vector<int> graph_from, vector<int> graph_to, vector<int> graph_weight, int source, int destination ) { if (source == destination) return 0; int m = graph_from.size(); vector<tuple<int, int, int>> edges; for (int i = 0; i < m; i++) { edges.push_back({graph_weight[i], graph_from[i], graph_to[i]}); } sort(edges.begin(), edges.end()); DSU dsu(graph_nodes); for (auto &edge : edges) { int weight, u, v; tie(weight, u, v) = edge; dsu.unite(u, v); if (dsu.find(source) == dsu.find(destination)) { return weight; } } return -1; }
Time complexity: O(m log m) due to sorting.
Space complexity: O(n + m).
pls give optimize corrct c++solution.
Use this optimized C++ solution. It uses two max-heaps: one for the first k employees and one for the last k employees.
cpp#include <bits/stdc++.h> using namespace std; long teamFormation(vector<int> score, int team_size, int k) { int n = score.size(); // pair = {score, -index} // Higher score is preferred. // If scores are equal, smaller index is preferred because -index is larger. priority_queue<pair<int, int>> leftHeap; priority_queue<pair<int, int>> rightHeap; int left = 0; int right = n - 1; // Add first k employees for (int i = 0; i < k && left <= right; i++) { leftHeap.push({score[left], -left}); left++; } // Add last k employees for (int i = 0; i < k && left <= right; i++) { rightHeap.push({score[right], -right}); right--; } long long ans = 0; for (int hired = 0; hired < team_size; hired++) { if (rightHeap.empty() || (!leftHeap.empty() && leftHeap.top() >= rightHeap.top())) { ans += leftHeap.top().first; leftHeap.pop(); if (left <= right) { leftHeap.push({score[left], -left}); left++; } } else { ans += rightHeap.top().first; rightHeap.pop(); if (left <= right) { rightHeap.push({score[right], -right}); right--; } } } return ans; }
For the sample:
cppscore = [17, 12, 10, 2, 7, 2, 11, 20, 8] team_size = 3 k = 4
Output:
cpp49
Time complexity: O(team_size * log k)
Space complexity: O(k)