include iostream include vector include algorithm using namespace std

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge
{
int a;
int b;
int cost;
};
vector<Edge> g;
vector <int> arr;
int comp(Edge a, Edge b)
{
return a.cost < b.cost;
}
int find(int v)
{
if (arr[v] == v)
return v;
else
{
arr[v] = find(arr[v]);
return arr[v];
}
}
void unite(int a, int b)
{
if (rand() % 2 == 0)
swap(a, b);
int pA = find(a);
int pB = find(b);
if (pA != pB)
{
arr[pA] = pB;
}
}
int main()
{
int n, m;
cin >> n >> m;
int a, b, cost;
for (int i = 0; i < m; ++i)
{
cin >> a >> b >> cost;
Edge temp;
a--;
b--;
temp.a = a;
temp.b = b;
temp.cost = cost;
g.push_back(temp);
}
vector<Edge> ans;
for (int i = 0; i < n; ++i)
{
arr.push_back(i);
}
sort(g.begin(), g.end(), comp);
int c = 0;
for (int i = 0; i < m; ++i)
{
if (find(g[i].a) != find(g[i].b))
{
ans.push_back(g[i]);
c += g[i].cost;
unite(g[i].a, g[i].b);
}
}
int c2 = 0;
int s = 600000;
for (int j = 0; j < n - 1; ++j)
{
for (int i = 0; i < n; ++i)
{
arr[i] = i;
}
int k = 0;
c2 = 0;
for (int i = 0; i < m; ++i)
{
if (ans[j].a != g[i].a && ans[j].b != g[i].b)
{
if (find(g[i].a) != find(g[i].b))
{
c2 += g[i].cost;
unite(g[i].a, g[i].b);
k++;
}
if (c2 < s && k == n - 1)
s = c2;
}
}
}
cout << c << endl;
if (s != 600000)
cout << c2;
return 0;
}