define _CRT_SECURE_NO_WARNI NGS include iostream include vector includ

 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
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
vector <int> a;
int fun(int v)
{
if (a[v] == v)
{
return v;
}
return a[v] = fun(a[v]);
}
void unite(int aa, int bb)
{
if (rand() % 2)
swap(aa, bb);
int a1 = fun(aa);
int b1 = fun(bb);
if (a1 != b1)
{
a[a1] = b1;
}
}
int main()
{
int n, m;
cin >> n >> m;
vector <vector <int> > vec(m, vector<int>(3));
a.resize(n);
for (int i = 0; i < n; i++)
{
a[i] = i;
}
for (int i = 0; i < m; i++)
{
scanf("%d %d %d", &vec[i][1], &vec[i][2], &vec[i][0]);
vec[i][1]--;
vec[i][2]--;
}
sort(vec.begin(), vec.end());
int s = 0;
vector <pair <int, int> > put;
for (int i = 0; i < m; i++)
{
if (fun(vec[i][1]) != fun(vec[i][2]))
{
unite(vec[i][1], vec[i][2]);
put.push_back(make_pair(vec[i][1], vec[i][2]));
s += vec[i][0];
}
}
cout << "Cost: " << s << endl;
int mini = 999999999;
for (int k = 0; k < put.size(); k++)
{
s = 0;
for (int i = 0; i < n; i++)
{
a[i] = i;
}
int qwe = 0;
for (int i = 0; i < m; i++)
{
if (!(put[k].first == vec[i][1] && put[k].second == vec[i][2]))
{
if (fun(vec[i][1]) != fun(vec[i][2])){
qwe++;
unite(vec[i][1], vec[i][2]);
s += vec[i][0];
}
}
}
if (qwe == n - 1 && s<mini)
{
mini = s;
}
}
if (mini == 999999999)
cout << "Cost: " << -1 << endl;
else
cout << "Cost: " << mini << endl;
return 0;
}