-
Notifications
You must be signed in to change notification settings - Fork 0
/
cats.cpp
96 lines (74 loc) · 1.59 KB
/
cats.cpp
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
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
struct DisjointSets{
int *parent, *rnk;
int n;
DisjointSets(int n){
this->n = n;
parent = new int[n+1];
rnk = new int[n+1];
for (int i = 0; i <= n; i++){
rnk[i] = 0;
parent[i] = i;
}
}
int find(int u){
if (u != parent[u])
parent[u] = find(parent[u]);
return parent[u];
}
void merge(int x, int y){
x = find(x), y = find(y);
if (rnk[x] > rnk[y])
parent[y] = x;
else
parent[x] = y;
if (rnk[x] == rnk[y])
rnk[y]++;
}
};
struct Graph{
int V, E;
vector<pair<int, pii>> edges;
Graph(int V, int E) : V(V), E(E){}
void add_edge(int u, int v, int w){
edges.push_back({w, {u, v}});
}
int kruskal_mst(){
int mst_wt = 0;
sort(edges.begin(), edges.end());
DisjointSets ds(V);
vector< pair<int, pii> >::iterator it;
for (it=edges.begin(); it!=edges.end(); it++){
int u = it->second.first;
int v = it->second.second;
int set_u = ds.find(u);
int set_v = ds.find(v);
if (set_u != set_v){
mst_wt += it->first;
ds.merge(set_u, set_v);
}
}
return mst_wt;
}
};
void solve(){
int milk, cats;
cin >> milk >> cats;
int edges = (cats * (cats - 1))/2;
Graph g(cats, edges);
for(int i=0; i<edges; i++){
int u, v, w;
cin >> u >> v >> w;
g.add_edge(u, v, w);
}
int mst_wt = g.kruskal_mst();
int total_needed = cats + mst_wt;
cout << (milk >= total_needed ? "yes" : "no") << endl;
}
int main(){
int t;
cin >> t;
while(t--) solve();
}