Skip to content

Commit 443ea4d

Browse files
committed
Added Solution - GfG to GitHub
1 parent afbd6f6 commit 443ea4d

File tree

1 file changed

+114
-0
lines changed

1 file changed

+114
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
//{ Driver Code Starts
2+
//Initial template for C++
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
// } Driver Code Ends
8+
//User function template for C++
9+
class Solution {
10+
int ans;
11+
private:
12+
int root(int i, vector<int> &parent)
13+
{
14+
while(parent[i]!=i)
15+
{
16+
parent[i] = parent[parent[i]];
17+
i = parent[i];
18+
}
19+
return i;
20+
}
21+
int Union(int a, int b, vector<int> &parent, vector<int> &sz)
22+
{
23+
int ra = root(a, parent);
24+
int rb = root(b, parent);
25+
if(ra == rb)
26+
return sz[ra]*sz[ra];
27+
if(sz[ra] < sz[rb])
28+
{
29+
swap(ra,rb);
30+
swap(a,b);
31+
}
32+
ans += sz[ra]*sz[rb];
33+
parent[rb] = ra;
34+
sz[ra] += sz[rb];
35+
return ans;
36+
}
37+
public:
38+
vector<int> maximumWeight(int n, vector<vector<int>> edges, int q, vector<int> &queries)
39+
{
40+
ans = 0;
41+
vector<int> parent(n+1, 0), sz(n+1, 0);
42+
for(int i = 0;i <= n; i++)
43+
{
44+
parent[i] = i;
45+
sz[i] = 1;
46+
}
47+
vector<pair<int, pair<int, int>>> wt;
48+
for(int i = 0; i < n-1; i++)
49+
wt.push_back({edges[i][2] , {edges[i][0], edges[i][1]}}); sort(wt.begin() , wt.end());
50+
map<int, int> mp;
51+
for(int i = 0;i < n-1; i++){
52+
int a = wt[i].first;
53+
int b = wt[i].second.first;
54+
int c = wt[i].second.second;
55+
mp[a] = Union(b, c, parent, sz);
56+
}
57+
vector<int> res;
58+
for(int i = 0; i < q; i++)
59+
{
60+
auto val = mp.upper_bound(queries[i]);
61+
if(val == mp.begin())
62+
res.push_back(0);
63+
else
64+
{
65+
val--;
66+
res.push_back(val->second);
67+
}
68+
}
69+
return res;
70+
71+
}
72+
73+
};
74+
75+
76+
77+
//{ Driver Code Starts.
78+
79+
int main()
80+
{
81+
int t;
82+
cin >> t;
83+
while (t--)
84+
{
85+
int n;
86+
cin >> n;
87+
88+
vector<vector<int>> edges(n-1, vector<int> (3, 0));
89+
90+
for(int i = 0; i < n-1; i++)
91+
{
92+
for(int j = 0; j < 3; j++)
93+
{
94+
cin >> edges[i][j];
95+
}
96+
}
97+
98+
int q;
99+
cin >> q;
100+
vector<int> queries(q);
101+
for(int i = 0; i < q; i++)
102+
cin >> queries[i];
103+
104+
Solution obj;
105+
vector<int> ans = obj.maximumWeight(n, edges, q, queries);
106+
107+
for(auto i:ans)
108+
cout << i << " ";
109+
cout << "\n";
110+
}
111+
return 0;
112+
}
113+
114+
// } Driver Code Ends

0 commit comments

Comments
 (0)