Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- import java.text.*;
- import java.math.*;
- import java.util.regex.*;
- class Edge{
- int from;
- int to;
- int weight;
- Edge(int from,int to, int weight){
- this.from = from;
- this.to = to;
- this.weight = weight;
- }
- }
- class DSU{
- int n;
- int[] parent;
- int[] sz;
- int connected;
- DSU(int n){
- this.n = n;
- this.parent = new int[n];
- this.sz = new int[n];
- this.connected = n;
- for(int i=0;i<n;i++){
- this.parent[i] = i;
- this.sz[i] = 1;
- }
- }
- int findParent(int u){
- while(u!=parent[u]){
- parent[u] = parent[parent[u]];
- u = parent[u];
- }
- return u;
- }
- void merge(int u,int v){
- int parU = findParent(u);
- int parV = findParent(v);
- if(parU == parV){
- return;
- }
- connected--;
- if(sz[parU] < sz[parV]){
- int temp = parU;
- parU = parV;
- parV = temp;
- }
- // merge
- parent[parV] = parU;
- sz[parU] += parV;
- sz[parV] = 0;
- }
- }
- // hello
- public class Solution {
- public int getGoodPaths(List<Edge> edgeList,int k){
- int numEdges = edgeList.size();
- int numVertices = numEdges + 1;
- DSU dsu = new DSU(numVertices);
- for(Edge e: edgeList){
- int u = e.from;
- int v = e.to;
- int w = e.weight;
- if(w<k){
- dsu.merge(u, v);
- }
- }
- int goodPaths = 0;
- for(int i=0;i<numVertices;i++){
- int value = dsu.sz[i];
- int totalContribution = ((value)*(value-1))/2;
- goodPaths += totalContribution;
- }
- return goodPaths;
- }
- public static void main(String[] args) {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement