diff --git a/src/DistributeWaterInVillage.java b/src/DistributeWaterInVillage.java new file mode 100644 index 0000000..37c322f --- /dev/null +++ b/src/DistributeWaterInVillage.java @@ -0,0 +1,44 @@ +import java.util.*; +public class DistributeWaterInVillage { + static int[] parent; + static int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { + parent = new int[n + 1]; + for (int i = 1; i <= n; i++) { + parent[i] = i; + } + List edges = new ArrayList<>(); + for (int[] pipe : pipes) { + edges.add(pipe); + } + for (int i = 1; i <= n; i++) { + edges.add(new int[] {0, i, wells[i - 1]}); + } + 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]; + parent[py] = px; + } + } + return result; + } + static int find(int x) { + if (parent[x] != x) parent[x] = find(parent[x]); + return parent[x]; + } + + public static void main(String[] args) { + int n = 3; + int[] wells = {1,2,2}; + int[][] pipes = {{1,2,1},{2,3,1}}; + + System.out.println("Minimum Cost To Supply water: "+ minCostToSupplyWater(n, wells, pipes)); + } +} diff --git a/src/FindCelebrity.java b/src/FindCelebrity.java new file mode 100644 index 0000000..b43808c --- /dev/null +++ b/src/FindCelebrity.java @@ -0,0 +1,41 @@ +public class FindCelebrity { + static int[][] graph; + static boolean knows(int a, int b) { + return graph[a][b] == 1; + } + static int findCelebrity(int n) { + int[] in = new int[n]; + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (knows(i, j)) { + in[i]--; + in[j]++; + } + if (knows(j, i)) { + in[j]--; + in[i]++; + } + } + } + + for (int i = 0; i < n; i++) { + if (in[i] == n - 1) return i; + } + + return -1; + } + + public static void main(String[] args) { + graph = new int[][] { + {1, 1, 0}, + {0, 1, 0}, + {1, 1, 1} + }; + int celebrity = findCelebrity(graph.length); + if (celebrity == -1) { + System.out.println("No celebrity found."); + } else { + System.out.println("Celebrity is person: " + celebrity); + } + } +}