0% found this document useful (0 votes)
16 views8 pages

Untitled Document

The document contains multiple Java classes that implement algorithms for graph-related problems, including finding the maximum weight node, detecting the largest sum cycle, and determining the nearest cell between two nodes. It also includes C++ functions for finding the least common descendant in a tree structure and calculating the shortest path between nodes. The algorithms utilize various data structures such as arrays, maps, and sets to efficiently solve the problems presented.

Uploaded by

harizibam.al22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views8 pages

Untitled Document

The document contains multiple Java classes that implement algorithms for graph-related problems, including finding the maximum weight node, detecting the largest sum cycle, and determining the nearest cell between two nodes. It also includes C++ functions for finding the least common descendant in a tree structure and calculating the shortest path between nodes. The algorithms utilize various data structures such as arrays, maps, and sets to efficiently solve the problems presented.

Uploaded by

harizibam.al22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

public class maximum_weight_node {

public static void main(String[] args) {


int[] edges = {4, 4, 1, 4, 13, 8, 8, 8, 0, 8, 14, 9, 15, 11, -1, 10, 15, 22, 22, 22, 22, 22, 21};

int[] weights = new int[edges.length];


int max = 0;
int maxWeight = 0;

for (int i = 0; i < edges.length; i++) {


int to = edges[i];

if (to != -1) {
weights[to] += edges[i];
if (max < weights[to]) {
max = weights[to];
maxWeight = to;
}
}
}

System.out.println(maxWeight);
}
}

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class largest_sum_cycle {


static int max = Integer.MIN_VALUE;
public static void main(String[] args) {
int[] edges = {4, 4, 1, 4, 13, 8, 8, 8, 0, 8, 14, 9, 15, 11, -1, 10, 15, 22, 22, 22, 22, 22, 21};

HashSet<Integer> visited = new HashSet<>();

for (int i = 0; i < edges.length; i++) {


if (!visited.contains(i)) {
Map<Integer, Integer> dist = new HashMap<>();
dist.put(i, 1);
dfs(edges, i, visited, dist);
}
}

System.out.println(max == Integer.MIN_VALUE ? -1 : max);


}

public static void dfs(int[] edges, int src, Set<Integer> visited, Map<Integer, Integer> dist) {
if (edges[src] != -1 && !visited.contains(src)) {
visited.add(src);

int neighbor = edges[src];


if (dist.containsKey(neighbor)) {
max = Math.max(max, dist.get(src) - dist.get(neighbor) + 1);
return;
}

dist.put(neighbor, dist.get(src) + 1);


dfs(edges, neighbor, visited, dist);
}
}
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

class Vertex {
public int vertex;
public int weigth;

public Vertex (int vertex, int weigth) {


this.vertex = vertex;
this.weigth = weigth;
}
}

public class Nearest{


public static void main(String[] args) {
int[] edges = {4, 4, 1, 4, 13, 8, 8, 8, 0, 8, 14, 9, 15, 11, -1, 10, 15, 22, 22, 22, 22, 22, 21};
int c1 = 9;
int c2 = 2;
int n = edges.length;

Map<Integer, List<Integer>> graph = buildGraph(edges);

int[] dist1 = bellmanFord(graph, edges, c1);


int[] dist2 = bellmanFord(graph, edges, c2);

System.out.println(Arrays.toString(dist1));
System.out.println(Arrays.toString(dist2));

int minDist = Integer.MAX_VALUE;


int nearestCell = -1;

for (int i = 0; i < n; i++) {


if (dist1[i] != Integer.MAX_VALUE && dist2[i] != Integer.MAX_VALUE) {
if (dist1[i] + dist2[i] < minDist) {
minDist = dist1[i] + dist2[i];
nearestCell = i;
}
}
}

System.out.println(nearestCell);
}

public static Map<Integer, List<Integer>> buildGraph(int[] edges) {


int n = edges.length;
Map<Integer, List<Integer>> graph = new HashMap<>();

for (int i = 0; i < n; i++) graph.put(i, new ArrayList<>());

for (int i = 0; i < n; i++) {


int to = edges[i];
if (to != -1) {
graph.get(i).add(to);
}
}

return graph;
}
/**
* WITH SIMPLE DFS
*/
public static void dfs(Map<Integer, List<Integer>> graph, int[][] dist, int src, int cell,
Set<Integer> v) {
if (v.contains(src)) return;

dist[src][cell] = v.size();
v.add(src);
for (int node: graph.get(src)) {
dfs(graph, dist, node, cell, v);
}
}

/**
* WITH DIJKSTRAS SHORTEST PATH ALGORITHM
*/
public static int[] dijkstra(Map<Integer, List<Integer>> graph, int src) {
int[] dist = new int[graph.size()];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;

Set<Integer> visited = new HashSet<>();


PriorityQueue<Vertex> heapq = new PriorityQueue<>((p1, p2) -> p1.weigth - p2.weigth);
heapq.add(new Vertex(src, 0));

while (!heapq.isEmpty()) {
Vertex v = heapq.poll();
int vertex = v.vertex;
int weigth = v.weigth;

if (visited.contains(vertex)) continue;
visited.add(vertex);

for (Integer neighbour: graph.get(vertex)) {


if (!visited.contains(neighbour)) {
dist[neighbour] = Math.min(dist[neighbour], weigth + 1);
heapq.add(new Vertex(neighbour, weigth + 1));
}
}
}

return dist;
}

/**
* WITH BELLMAN FORD SHORTEST PATH ALGORITM
*/
public static int[] bellmanFord(Map<Integer, List<Integer>> graph, int[] edges, int src) {
int n = graph.size();
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;

for (int i = 0; i < n - 1; i++) {


for (int u = 0; u < n; u++) {
int v = edges[u];
if (v != -1 && dist[u] != Integer.MAX_VALUE) {
dist[v] = Math.min(dist[v], dist[u] + 1);
}
}
}

return dist;
}
}

int leastCommonDescendent(int nodes[], int N, int node1, int node2){


int *visited = new int [N];
int cnt1 = 0; //used for counting length of path from node1 to node2
int cnt2 = 0; //used for counting length of path from node2 to node1
int mark = node1; //storing as a marker needed later for detecting end of
search

if(node1 == node2) return node2;


for(int i = 0; i < N; i++){
visited[i] = 0;
}

while((nodes[node1] != node1) && (nodes[node1] != -1) && (visited[node1] ==


0) && (node1 != node2)){
visited[node1]++;
node1 = nodes[node1];
cnt1++;
}

visited[node1]++; //so that first node in cycle has count 2


//if find a node in 2nd iteration that has count 2
//such that when node1 == node2 it means we are in the same
subgraph
//elsif node1 != node2 we are in different sub graphs

while((nodes[node2] != node2) && (nodes[node2] != -1) && (visited[node2] !=


2) && (node1 != node2)){
visited[node2]++;
node2 = nodes[node2];
cnt2++;
}
//In below case the nodes are in different disjoint subgraphs
//and both subgraphs have loops so node1 can never be equal to node2
//cout << visited[node1] << visited[node2] << endl;
if(node1 != node2) return -1;
//In below case both nodes are in different disjoint subgraphs
//but there is no loop in 1st one(containing node1)
//and 2nd one has a loop
if ((nodes[node1] == -1) && (visited[node2] == 1)) return -1;
//In below case both nodes are in different disjoint subgraphs
//but 1st one has a loop and second one doesn't
if(nodes[node2] == -1) return -1;
//In below case both nodes are in same subgraph so we
//need to check the length of two alternate paths
if(cnt1 > cnt2)
return node2;
else
return mark;
}

int solution(vector<int> arr, int src, int dest){


// Two maps, visA for distance from src and visB for distance from dest
// They serve two purpose, if visA[x] == 0, that means we haven't reached
that node yet,
// and if it holds any value, say d, that means it is d distance away from
the particular node
map<int,int> visA,visB;
int start = arr[src];
int curr = 1;
set<int> s; // contains unique set of nodes to check at last

// iniitializing final nodes


for(auto &x: arr){
s.insert(x);
}
// traversing until we get to a cell where we've already reached
while(visA[start] == 0){
visA[start] = curr; // Marcking the distance
curr++;
start = arr[start];
if(start == -1){
break; // Getting out if we get to a node who is not pointing at
any other node
}
}
start = arr[dest];
// Same logic as above but traversing from dest
while(visB[start] == 0){
visB[start] = curr;
curr++;
start = arr[start];
if(start == -1){
break;
}
}
// This is an array of two values, vp[i].first holds the sum of distance of
vp[i].second from src and dest.
vector<pair<int,int>> vp;
for(auto &x: s){
if(visA[x] != 0 && visB[x] != 0){ // Checking if we ever got to that
particular node from both src and dest or not
pair<int,int> p = {visA[x] + visB[x], x};
vp.push_back(p);
}
}
// sorting and finding the node with list sum of visA[} + visB[]
sort(vp.begin(), vp.end());
return vp[0].second;
}

int solution(vector<int>arr){
int ans=INT_MIN;
int result=-1;
vector<int>weight(arr.size(),0);
for(int i=0;i<arr.size();i++){
int source=i;
int dest=arr[i];
if(dest!=-1){
weight[dest]+=source;
if(ans<=weight[dest]){
ans=max(ans,weight[dest]);
result=dest;
}

}
}
if(ans!=INT_MIN)
return result;
return -1;
}

You might also like