Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- using std::vector;
- void DFS(int v, vector<vector<int>>& neighbours, vector<bool>& used, int num_of_component) {
- used[v] = true;
- for (int to : neighbours[v]) {
- if (used[to]) {
- continue;
- }
- DFS(to, neighbours, used, num_of_component);
- }
- }
- int NumOfComponents(vector<vector<int>>& neighbours, int n) {
- vector<bool> used(n, false);
- int num_of_component = 1;
- for (int i = 0; i < n; ++i) {
- if (!used[i]) {
- DFS(i, neighbours, used, num_of_component++);
- }
- }
- return num_of_component - 1;
- }
- vector<vector<int>> SelectAppropriateGraph(vector<vector<std::pair<int, int>>>& neighboursWithWeight, int x, int n) {
- vector<vector<int>> appropriateGraph(n);
- for (int i = 0; i < neighboursWithWeight.size(); ++i) {
- for (int j = 0; j < neighboursWithWeight[i].size(); ++j) {
- if (neighboursWithWeight[i][j].second > x) {
- appropriateGraph[i].push_back(neighboursWithWeight[i][j].first);
- }
- }
- }
- return std::move(appropriateGraph);
- }
- int BinaryFindAnswer(vector<vector<std::pair<int, int>>>& neighboursWithWeight, int max, int initialNum, int n) {
- int left = 0;
- int right = max;
- while (left <= right) {
- int middle = (left + right) / 2;
- vector<vector<int>> neighbours = SelectAppropriateGraph(neighboursWithWeight, middle, n);
- if (NumOfComponents(neighbours, n) == initialNum) { // то есть можно попробовать больше снести
- left = middle + 1;
- } else { // то есть надо меньше снести
- right = middle - 1;
- }
- }
- vector<vector<int>> neighbours = SelectAppropriateGraph(neighboursWithWeight, left, n);
- if (NumOfComponents(neighbours, n) == initialNum) return left;
- return left - 1;
- }
- int main() {
- int n, m;
- std::cin >> n >> m;
- vector<vector<std::pair<int, int>>> neighboursWithWeight(n);
- vector<vector<int>> neighbours(n);
- int maxWeight = 0;
- for (int j = 0; j < m; ++j) {
- int l, r, w;
- std::cin >> l >> r >> w;
- maxWeight = std::max(maxWeight, w);
- if (l == r) continue; // ok?
- neighboursWithWeight[l - 1].emplace_back(r - 1, w);
- neighboursWithWeight[r - 1].emplace_back(l - 1, w);
- neighbours[l - 1].push_back(r - 1);
- neighbours[r - 1].push_back(l - 1);
- }
- int initialNumOfComponents = NumOfComponents(neighbours, n);
- std::cout << BinaryFindAnswer(neighboursWithWeight, maxWeight, initialNumOfComponents, n);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement