Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/DistributeWaterInVillage.java
Original file line number Diff line number Diff line change
@@ -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<int[]> 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));
}
}
41 changes: 41 additions & 0 deletions src/FindCelebrity.java
Original file line number Diff line number Diff line change
@@ -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);
}
}
}