0% found this document useful (0 votes)
9 views24 pages

Daa Record Ii

Uploaded by

20bel513
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)
9 views24 pages

Daa Record Ii

Uploaded by

20bel513
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/ 24

7.

PRIM’S AND KRUSKAL’S ALGORITHM

import java.util.*;
public class MSTAlgorithms {
static class Edge implements Comparable<Edge> {
int src, dest, weight;
public Edge(int src, int dest, int weight) {
this.src = src;
this.dest = dest;
this.weight = weight;
}
@Override
public int compareTo(Edge other) {
return Integer.compare(this.weight, other.weight);
}
}
static class Graph {
int V;
List<List<Edge>> adjList;
public Graph(int V) {
this.V = V;
adjList = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adjList.add(new ArrayList<>());
}
}
public void addEdge(int src, int dest, int weight) {
adjList.get(src).add(new Edge(src, dest, weight));
adjList.get(dest).add(new Edge(dest, src, weight));
}
}
static class UnionFind {
int[] parent;
int[] rank;
public UnionFind(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public int find(int u) {
if (parent[u] != u) {
parent[u] = find(parent[u]);
}
return parent[u];
}
public boolean union(int u, int v) {
int pu = find(u);
int pv = find(v);
if (pu == pv) {
return false;
}
if (rank[pu] < rank[pv]) {
parent[pu] = pv;
} else if (rank[pu] > rank[pv]) {
parent[pv] = pu;
} else {
parent[pv] = pu;
rank[pu]++;
}
return true;
}
}
static List<Edge> primMST(Graph graph) {
boolean[] inMST = new boolean[graph.V];
PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(e -> e.weight));
List<Edge> MST = new ArrayList<>();
long startTime = System.nanoTime();
Arrays.fill(inMST, false);
inMST[0] = true;
pq.addAll(graph.adjList.get(0));
while (!pq.isEmpty()) {
Edge minEdge = pq.poll();
if (!inMST[minEdge.dest]) {
inMST[minEdge.dest] = true;
MST.add(minEdge);
for (Edge adjEdge : graph.adjList.get(minEdge.dest)) {
if (!inMST[adjEdge.dest]) {
pq.add(adjEdge);
}
}
}
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("Time taken for Prim's algorithm: " + duration + " nanoseconds");
return MST;
}
static List<Edge> kruskalMST(Graph graph) {
List<Edge> edges = new ArrayList<>();
for (List<Edge> list : graph.adjList) {
edges.addAll(list);
}
Collections.sort(edges);
UnionFind uf = new UnionFind(graph.V);
List<Edge> MST = new ArrayList<>();
long startTime = System.nanoTime();
for (Edge edge : edges) {
if (uf.union(edge.src, edge.dest)) {
MST.add(edge);
}
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("Time taken for Kruskal's algorithm: " + duration + " nanoseconds");
return MST;
}
public static void main(String[] args) {
int V = 9;
Graph graph = new Graph(V);
graph.addEdge(0, 1, 6);
graph.addEdge(0, 7, 7);
graph.addEdge(1, 7, 3);
graph.addEdge(1, 2, 2);
graph.addEdge(7, 8, 7);
graph.addEdge(7, 6, 11);
graph.addEdge(2, 8, 9);
graph.addEdge(8, 6, 2);
graph.addEdge(2, 5, 7);
graph.addEdge(2, 3, 10);
graph.addEdge(6, 8, 3);
graph.addEdge(3, 5, 7);
graph.addEdge(3, 4, 5);
graph.addEdge(5, 4, 6);
graph.addEdge(5, 6, 4);

List<Edge> primMST = primMST(graph);


List<Edge> kruskalMST = kruskalMST(graph);
System.out.println("\nPrim's MST:");
for (Edge edge : primMST) {
System.out.println(edge.src + " - " + edge.dest + ": " + edge.weight);
}
System.out.println("\nKruskal's MST:");
for (Edge edge : kruskalMST) {
System.out.println(edge.src + " - " + edge.dest + ": " + edge.weight);
}
}
}
OUTPUT
8. MULTISTAGE GRAPH

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MultistageGraph {
static class Edge {
int target;
int weight;
Edge(int target, int weight) {
this.target = target;
this.weight = weight;
}
}
static void findShortestPath(List<List<Edge>> graph, int numStages) {
int[] dist = new int[graph.size()];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[0] = 0;
for (int i = 0; i < numStages - 1; i++) {
List<Edge> currentStage = graph.get(i);
for (Edge edge : currentStage) {
int current = i;
int target = edge.target;
int weight = edge.weight;
if (dist[current] + weight < dist[target]) {
dist[target] = dist[current] + weight;
}
}
}
int lastStage = graph.size() - 1;
System.out.println("Shortest distance from stage 0 to stage " + lastStage + " is: " + dist[lastStage]);
}
public static void main(String[] args) {
int numStages = 5;
List<List<Edge>> graph = new ArrayList<>(numStages);
for (int i = 0; i < numStages; i++) {
graph.add(new ArrayList<>());
}
graph.get(0).add(new Edge(1, 10));
graph.get(0).add(new Edge(2, 5));
graph.get(1).add(new Edge(2, 3));
graph.get(1).add(new Edge(3, 1));
graph.get(2).add(new Edge(3, 8));
graph.get(2).add(new Edge(4, 4));
graph.get(3).add(new Edge(4, 2));
findShortestPath(graph, numStages);
}
}

OUTPUT
9. DIJKSTRA'S ALGORITHM
import java.util.*;
public class Dijkstra {
static class Edge {
int target;
int weight;
Edge(int target, int weight) {
this.target = target;
this.weight = weight;
}
}
static class NodeDistance implements Comparable<NodeDistance> {
int node;
int distance;
NodeDistance(int node, int distance) {
this.node = node;
this.distance = distance;
}
@Override
public int compareTo(NodeDistance other) {
return Integer.compare(this.distance, other.distance);
}
}
static int[] dijkstra(List<List<Edge>> graph, int start) {
int n = graph.size();
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
PriorityQueue<NodeDistance> pq = new PriorityQueue<>();
pq.add(new NodeDistance(start, 0));
while (!pq.isEmpty()) {
NodeDistance currentNode = pq.poll();
int current = currentNode.node;
int currentDistance = currentNode.distance;
if (currentDistance > dist[current]) {
continue;
}
for (Edge edge : graph.get(current)) {
int neighbor = edge.target;
int weight = edge.weight;
int newDist = dist[current] + weight;
if (newDist < dist[neighbor]) {
dist[neighbor] = newDist;
pq.add(new NodeDistance(neighbor, newDist));}
}
}
return dist;
}
public static void main(String[] args) {
List<List<Edge>> graph = new ArrayList<>();
int numNodes = 6;
for (int i = 0; i < numNodes; i++) {
graph.add(new ArrayList<>());
}
graph.get(0).add(new Edge(1, 7));
graph.get(0).add(new Edge(2, 9));
graph.get(0).add(new Edge(5, 14));
graph.get(1).add(new Edge(2, 10));
graph.get(1).add(new Edge(3, 15));
graph.get(2).add(new Edge(3, 11));
graph.get(2).add(new Edge(5, 2));
graph.get(3).add(new Edge(4, 6));
graph.get(4).add(new Edge(5, 9));
int start = 0;
int[] distances = dijkstra(graph, start);
System.out.println("Shortest distances from start node " + start + ":");
for (int i = 0; i < numNodes; i++) {
System.out.println("To node " + i + ": " + distances[i]);
}
}}
OUTPUT
10. SUBSET-SUM
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class Subset {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] nums = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
nums[i] = scanner.nextInt();
}
System.out.print("Enter the target sum: ");
int targetSum = scanner.nextInt();
scanner.close();
List<List<Integer>> subsets = findSubsetSumPairs(nums, targetSum);
System.out.println("Equivalent Pairs " + targetSum + ":");
for (List<Integer> subset : subsets) {
System.out.println(subset);
}
}
public static List<List<Integer>> findSubsetSumPairs(int[] nums, int targetSum) {
List<List<Integer>> subsets = new ArrayList<>();
Stack<State> stack = new Stack<>();
stack.push(new State(0, new ArrayList<>(), targetSum));
while (!stack.isEmpty()) {
State currentState = stack.pop();
int index = currentState.index;
List<Integer> currentSubset = currentState.currentSubset;
int remainingSum = currentState.remainingSum;
if (remainingSum == 0 && currentSubset.size() == 2) {
subsets.add(new ArrayList<>(currentSubset));
continue; // Skip further processing for this state
}
for (int i = index; i < nums.length; i++) {
if (nums[i] <= remainingSum) {
List<Integer> newSubset = new ArrayList<>(currentSubset);
newSubset.add(nums[i]);
stack.push(new State(i + 1, newSubset, remainingSum - nums[i]));
}
}
}
return subsets;
}
static class State {
int index;
List<Integer> currentSubset;
int remainingSum;
public State(int index, List<Integer> currentSubset, int remainingSum) {
this.index = index;
this.currentSubset = currentSubset;
this.remainingSum = remainingSum;
}
}
}

OUTPUT
11. N-QUEENS PROBLEM
import java.util.Scanner;
public class N_QUEEN {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter N: ");
int n = scanner.nextInt();
scanner.close();
solveNQueens(n);
}
public static void solveNQueens(int n) {
int[][] board = new int[n][n];
if (solveNQueensUtil(board, 0, n)) {
printBoard(board);
} else {
System.out.println("Solution does not exist");
}
}
public static boolean solveNQueensUtil(int[][] board, int col, int n) {
if (col >= n)
return true;
for (int i = 0; i < n; i++) {
if (isSafe(board, i, col, n)) {
board[i][col] = 1;
if (solveNQueensUtil(board, col + 1, n))
return true;
board[i][col] = 0;
}
}
return false;
}
public static boolean isSafe(int[][] board, int row, int col, int n) {
int i, j;
for (i = 0; i < col; i++)
if (board[row][i] == 1)
return false;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1)
return false;
for (i = row, j = col; j >= 0 && i < n; i++, j--)
if (board[i][j] == 1)
return false;
return true;
}
public static void printBoard(int[][] board) {
int n = board.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}

OUTPUT
12. HAMILTONIAN CYCLE
import java.util.Arrays;
public class HamiltonianCycle {
private int V;
private int[][] graph;
public HamiltonianCycle(int[][] graph) {
this.graph = graph;
this.V = graph.length;
}
private boolean isSafe(int v, int pos, int[] path, boolean[] visited) {
if (graph[path[pos - 1]][v] == 0)
return false;
if (visited[v])
return false;
return true;
}
private boolean hamCycleUtil(int[] path, int pos, boolean[] visited) {
if (pos == V) {
if (graph[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
}
for (int v = 1; v < V; v++) {
if (isSafe(v, pos, path, visited)) {
path[pos] = v;
visited[v] = true;
if (hamCycleUtil(path, pos + 1, visited))
return true;
path[pos] = -1;
visited[v] = false;
}
}
return false;
}
public boolean hamCycle() {
int[] path = new int[V];
Arrays.fill(path, -1);
boolean[] visited = new boolean[V];
path[0] = 0;
visited[0] = true;
if (!hamCycleUtil(path, 1, visited)) {
System.out.println("SoluƟon does not exist");
return false;
}
printSolution(path);
return true;
}
private void printSolution(int[] path) {
System.out.println("Hamiltonian Cycle exists: ");
for (int i = 0; i < V; i++)
System.out.print(path[i] + " ");
System.out.println(path[0]);
}
public static void main(String[] args) {
int[][] graph = {
{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{1, 0, 0, 1, 1},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0}
};
HamiltonianCycle hamiltonianCycle = new HamiltonianCycle(graph);
hamiltonianCycle.hamCycle();
}
}

OUTPUT
13. ASSIGNMENT PROBLEM
import java.util.*;
public class AssignmentProblem {
public static int findMinCost(int[][] cost) {
int n = cost.length;
int[] assignedTask = new int[n];
int[] assignedAgent = new int[n];
Arrays.fill(assignedTask, -1);
Arrays.fill(assignedAgent, -1);
int[] taskCost = new int[n];
Arrays.fill(taskCost, Integer.MAX_VALUE);
PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingInt(node ->
node.cost));
for (int i = 0; i < n; i++)
pq.offer(new Node(cost[0][i], 0, i));
while (!pq.isEmpty()) {
Node top = pq.poll();
if (assignedTask[top.task] == -1 && taskCost[top.task] > top.cost) {
assignedTask[top.task] = top.agent;
assignedAgent[top.agent] = top.task;
taskCost[top.task] = top.cost;
}
if (top.task < n - 1) {
for (int i = 0; i < n; i++) {
if (assignedAgent[i] == -1) {
int newCost = top.cost + cost[top.task + 1][i];
pq.offer(new Node(newCost, top.task + 1, i));
}
}
}
}
int minCost = 0;
for (int i = 0; i < n; i++) {
minCost += cost[i][assignedTask[i]];
}
return minCost;
}
static class Node {
int cost;
int task;
int agent;
public Node(int cost, int task, int agent) {
this.cost = cost;
this.task = task;
this.agent = agent;
}
}
public static void main(String[] args) {
int[][] cost = {
{9, 2, 2, 8},
{2, 4, 3, 7},
{8, 8, 7, 8},
{1, 6, 9, 4}
};
System.out.println("Minimum cost: " + findMinCost(cost));
}
}

OUTPUT
14. KNAPSACK PROBLEM
import java.util.Arrays;
class KnapsackItem implements Comparable<KnapsackItem> {
int weight;
int value;
double ratio;
public KnapsackItem(int weight, int value) {
this.weight = weight;
this.value = value;
this.ratio = (double) value / weight;
}
@Override
public int compareTo(KnapsackItem other) {
return Double.compare(other.ratio, this.ratio);
}
}
public class Knapsack {
static int knapsack(int capacity, KnapsackItem[] items) {
Arrays.sort(items);
int n = items.length;
int currentWeight = 0;
int currentValue = 0;
int maxPossibleValue = 0;
for (int i = 0; i < n; i++) {
if (currentWeight + items[i].weight <= capacity) {
currentWeight += items[i].weight;
currentValue += items[i].value;
} else {
int remainingCapacity = capacity - currentWeight;
maxPossibleValue += items[i].ratio * remainingCapacity;
break;
}
}
return branchAndBound(0, capacity, 0, 0, maxPossibleValue, items);
}
static int branchAndBound(int index, int capacity, int currentWeight, int
currentValue, double maxPossibleValue, KnapsackItem[] items){
if (index == items.length || capacity == 0)
return currentValue;
if (currentWeight + items[index].weight > capacity)
return currentValue;
if (maxPossibleValue <= currentValue)
return currentValue;
int include = branchAndBound(index + 1, capacity - items[index].weight,
currentWeight + items[index].weight,
currentValue + items[index].value, maxPossibleValue, items);
int exclude = branchAndBound(index + 1, capacity, currentWeight, currentValue, maxPossibleValue,
items);
return Math.max(include, exclude);
}
public static void main(String[] args) {
KnapsackItem[] items = {
new KnapsackItem(10, 60),
new KnapsackItem(20, 50),
new KnapsackItem(30, 120)
};
int capacity = 50;
int maxValue = knapsack(capacity, items);
System.out.println("Maximum value that can be obtained: " + maxValue);
}
}

OUTPUT
15. TRAVELLING SALESMAN PROBLEM
import java.util.*;
public class TravellingSalesman {
static class TSPNode implements Comparable<TSPNode> {
int vertex;
int level;
int[] path;
int cost;
boolean[] visited;
public TSPNode(int vertex, int level, int[] path, int cost, boolean[] visited) {
this.vertex = vertex;
this.level = level;
this.path = Arrays.copyOf(path, path.length);
this.cost = cost;
this.visited = Arrays.copyOf(visited, visited.length);
}
@Override
public int compareTo(TSPNode other) {
return Integer.compare(this.cost, other.cost);
}
}
static int tsp(int[][] graph, List<Integer> optimalPath) {
int n = graph.length;
PriorityQueue<TSPNode> pq = new PriorityQueue<>();
boolean[] visited = new boolean[n];
int[] path = new int[n];
Arrays.fill(visited, false);
Arrays.fill(path, -1);
visited[0] = true;
path[0] = 0;
TSPNode root = new TSPNode(0, 0, path, 0, visited);
root.cost = bound(root, graph);
pq.add(root);
while (!pq.isEmpty()) {
TSPNode currentNode = pq.poll();
if (currentNode.level == n - 1) {
currentNode.cost += graph[currentNode.vertex][0];
updateOptimalPath(currentNode, optimalPath);
return currentNode.cost;
}
for (int i = 0; i < n; i++) {
if (!currentNode.visited[i]) {
TSPNode childNode = new TSPNode(i, currentNode.level + 1,
currentNode.path, currentNode.cost + graph[currentNode.vertex][i],
currentNode.visited.clone());
childNode.visited[i] = true;
childNode.path[childNode.level] = i;
childNode.cost = bound(childNode, graph);
pq.add(childNode);
}
}
}
return -1;
}
static int bound(TSPNode node, int[][] graph) {
int n = graph.length;
boolean[] visited = node.visited.clone();
visited[node.vertex] = true;
int cost = node.cost;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
int minEdge = Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
if (i != j && !visited[j]) {
minEdge = Math.min(minEdge, graph[i][j]);
}
}
cost += minEdge;
}
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
int minEdge = Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
if (i != j && !visited[j]) {
minEdge = Math.min(minEdge, graph[i][j]);
}
}
cost += minEdge;
}
}
return cost;
}
static void updateOptimalPath(TSPNode node, List<Integer> optimalPath) {
for (int city : node.path) {
optimalPath.add(city);
}
optimalPath.add(0);
}
public static void main(String[] args) {
int[][] graph = {
{0, 10, 15, 20},
{15, 0, 35, 15},
{55, 35, 0, 30},
{20, 20, 30, 0}
};
List<Integer> optimalPath = new ArrayList<>();
int minCost = tsp(graph, optimalPath);
System.out.println("Minimum cost for TSP: " + minCost);
System.out.println("Optimal path: " + optimalPath);
}
}
OUTPUT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy