Advertisement
aqibm

Untitled

Apr 22nd, 2025
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | Source Code | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6.  
  7.  
  8. class Edge{
  9.     int from;
  10.     int to;
  11.     int weight;
  12.    
  13.     Edge(int from,int to, int weight){
  14.         this.from = from;
  15.         this.to = to;
  16.         this.weight = weight;
  17.     }
  18. }
  19.  
  20. class DSU{
  21.     int n;
  22.     int[] parent;
  23.     int[] sz;
  24.     int connected;
  25.    
  26.     DSU(int n){
  27.         this.n = n;
  28.         this.parent = new int[n];
  29.         this.sz = new int[n];
  30.         this.connected = n;
  31.         for(int i=0;i<n;i++){
  32.             this.parent[i] = i;
  33.             this.sz[i] = 1;
  34.         }
  35.     }
  36.    
  37.     int findParent(int u){
  38.         while(u!=parent[u]){
  39.             parent[u] = parent[parent[u]];
  40.             u = parent[u];
  41.         }
  42.         return u;
  43.     }
  44.    
  45.     void merge(int u,int v){
  46.         int parU = findParent(u);
  47.         int parV = findParent(v);
  48.         if(parU == parV){
  49.             return;
  50.         }
  51.         connected--;
  52.         if(sz[parU] < sz[parV]){
  53.             int temp = parU;
  54.             parU = parV;
  55.             parV = temp;
  56.         }
  57.         // merge
  58.         parent[parV] = parU;
  59.         sz[parU] += parV;
  60.         sz[parV] = 0;
  61.     }
  62. }
  63.  
  64. // hello
  65. public class Solution {
  66.     public int getGoodPaths(List<Edge> edgeList,int k){
  67.         int numEdges = edgeList.size();
  68.         int numVertices = numEdges + 1;
  69.         DSU dsu = new DSU(numVertices);
  70.         for(Edge e: edgeList){
  71.             int u = e.from;
  72.             int v = e.to;
  73.             int w = e.weight;
  74.             if(w<k){
  75.                 dsu.merge(u, v);
  76.             }
  77.         }
  78.         int goodPaths = 0;
  79.         for(int i=0;i<numVertices;i++){
  80.             int value = dsu.sz[i];
  81.             int totalContribution = ((value)*(value-1))/2;
  82.             goodPaths += totalContribution;
  83.         }
  84.         return goodPaths;
  85.     }
  86.  
  87.  
  88.     public static void main(String[] args) {
  89.        
  90.     }
  91. }
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement