diff --git a/Find Celebrity.java b/Find Celebrity.java new file mode 100644 index 0000000..2510d8a --- /dev/null +++ b/Find Celebrity.java @@ -0,0 +1,24 @@ +/* The knows API is defined in the parent class Relation. + boolean knows(int a, int b); */ + + public class Solution extends Relation { + public int findCelebrity(int n) { + int celeb=0; + for(int i=1;iceleb){ + if(!knows(i,celeb)) return -1; + } + } + + return celeb; + } + } \ No newline at end of file diff --git a/WaterDistribution.java b/WaterDistribution.java new file mode 100644 index 0000000..1884ffd --- /dev/null +++ b/WaterDistribution.java @@ -0,0 +1,44 @@ +class Solution { + int[] uf; + public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { + this.uf=new int[n+1]; + for(int i=0;i<=n;i++){ + uf[i]=i; + } + List edges=new ArrayList<>(); + for(int i=1;i<=n;i++){ + edges.add(new int[]{0,i,wells[i-1]}); + } + + for(int[] pipe:pipes){ + edges.add(pipe); + } + + int result=0; + Collections.sort(edges,(a,b)->a[2]-b[2]); + + + for(int[] edge:edges){ + int x=edge[0]; + int y=edge[1]; + + int px=find(x); + int py=find(y); + + if(px!=py){ + result+=edge[2]; + uf[px]=py; + } + } + + return result; + } + + + private int find(int x){ + if(uf[x]!=x){ + uf[x]=find(uf[x]); + } + return uf[x]; + } +} \ No newline at end of file