-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15_noofgoodpaths.cpp
More file actions
36 lines (35 loc) · 830 Bytes
/
15_noofgoodpaths.cpp
File metadata and controls
36 lines (35 loc) · 830 Bytes
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
//https://leetcode.com/problems/number-of-good-paths/description/
class Solution {
public:
int find(vector<int>& y,int i) {
if(i==y[i]) return i;
y[i]=find(y,y[i]);
return y[i];
}
int numberOfGoodPaths(vector<int>& vals, vector<vector<int>>& edges) {
int n = vals.size(),m=edges.size(),ans=0;
vector<vector<int>> x(n);
vector<int> y(n);
for(int i=0;i<n;i++){
y[i]=i;
x[i]={vals[i],1};
}
sort(edges.begin(),edges.end(),[&](vector<int>& a,vector<int>& b){
return max(vals[a[0]],vals[a[1]])<max(vals[b[0]],vals[b[1]]);
});
for(int i=0;i<m;i++){
int a=find(y,edges[i][0]);
int b=find(y,edges[i][1]);
if(x[a][0]!=x[b][0]){
if(x[a][0]>x[b][0]) y[b]=a;
else y[a]=b;
}
else{
y[a]=b;
ans+=x[a][1]*x[b][1];
x[b][1]+=x[a][1];
}
}
return ans+n;
}
};