Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

WEEK:8 PROGRAM-1

1. Assume that a project of road construction to connect some cities is given to your
friend. Map of these cities and roads which will connect them (after construction) is
provided to him in the form of a graph. Certain amount of rupees is associated with
construction of each road. Your friend has to calculate the minimum budget required
for this project. The budget should be designed in such a way that the cost of connecting
the cities should be minimum and number of roads required to connect all the cities
should be minimum (if there are N cities then only N-1 roads need to be constructed).
He asks you for help. Now, you have to help your friend by designing an algorithm
which will find minimum cost required to connect these cities. (use Prim's algorithm).

SOURCE CODE

#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
int graph[100][100];
int minCost[100];
bool visited[100];
int calculateMinBudget(int numCities) {
    for (int city = 0; city < numCities; city++) {
        minCost[city] = INT_MAX;
        visited[city] = false;  }
    minCost[0] = 0;
    for (int count = 0; count < numCities - 1; count++) {
        int minCostVal = INT_MAX;
        int minCostCity = -1, currentCity;
        for (currentCity = 0; currentCity < numCities; currentCity++) {
            if (!visited[currentCity] && minCost[currentCity] < minCostVal) {
                minCostVal = minCost[currentCity];
                minCostCity = currentCity;
            }   }
        visited[minCostCity] = true;
        for (currentCity = 0; currentCity < numCities; currentCity++) {
            if (graph[minCostCity][currentCity] && !visited[currentCity] &&
                graph[minCostCity][currentCity] < minCost[currentCity]) {
                minCost[currentCity] = graph[minCostCity][currentCity];
            }   }   }
    int totalCost = 0;
    for (int city = 0; city < numCities; city++) {
        totalCost += minCost[city]; }
    return totalCost;   }
int main(){
    int minibudget, numCities,i,j;
    printf("Enter the number of cities: ");
    scanf("%d", &numCities);
    printf("Enter the costs of connecting cities:\n");
    for (i = 0; i < numCities; i++) {
        for (j = 0; j < numCities; j++) {
            scanf("%d", &graph[i][j]);
        }   }
    minibudget = calculateMinBudget(numCities);
    printf("Minimum budget required for the project: %d\n", minibudget);
    return 0;      
}  

OUTPUT
PROGRAM-2

2. Implement the previous problem using Kruskal's algorithm.

SOURCE CODE
#include <stdio.h>
#include <stdlib.h>
typedef struct {
    int src, dest, weight;
} Edge;
typedef struct {
    int parent;
    int rank;
} Subset;
typedef struct {
    int numCities;
    int numEdges;
    Edge edges[100];
} Graph;
Graph* createGraph(int numCities, int numEdges) {
    Graph* graph = (Graph*)malloc(sizeof(Graph));
    graph->numCities = numCities;
    graph->numEdges = numEdges;
    return graph;
}
int find(Subset subsets[], int i) {
    if (subsets[i].parent != i) {
        subsets[i].parent = find(subsets, subsets[i].parent);
    }
    return subsets[i].parent;
}
void unionSet(Subset subsets[], int x, int y) {
    int xRoot = find(subsets, x);
    int yRoot = find(subsets, y);
    if (subsets[xRoot].rank < subsets[yRoot].rank) {
        subsets[xRoot].parent = yRoot;
    } else if (subsets[xRoot].rank > subsets[yRoot].rank) {
        subsets[yRoot].parent = xRoot;
    } else {
        subsets[yRoot].parent = xRoot;
        subsets[xRoot].rank++;
    }
}
int compareEdges(const void* a, const void* b) {
    Edge* edgeA = (Edge*)a;
    Edge* edgeB = (Edge*)b;
    return edgeA->weight - edgeB->weight;
}
void kruskalMST(Graph* graph) {
    int numCities = graph->numCities;
    Edge result[numCities - 1];
    Subset* subsets = (Subset*)malloc(numCities * sizeof(Subset));
    int i = 0;
    int e = 0;
    for (i = 0; i < numCities; i++) {
        subsets[i].parent = i;
        subsets[i].rank = 0;
    }
    qsort(graph->edges, graph->numEdges, sizeof(Edge), compareEdges);
    i = 0;
    while (e < numCities - 1) {
        Edge nextEdge = graph->edges[i++];
        int x = find(subsets, nextEdge.src);
        int y = find(subsets, nextEdge.dest);
        if (x != y) {
            result[e++] = nextEdge;
            unionSet(subsets, x, y);
        }
    }
    int totalCost = 0;
    printf("Minimum cost to connect all cities:\n");
    for (i = 0; i < e; i++) {
        printf("%d -- %d\tCost: %d\n", result[i].src, result[i].dest,
result[i].weight);
        totalCost += result[i].weight;
    }
    printf("Total cost: %d\n", totalCost);
    free(subsets);
}
int main() {
    int numCities, numEdges;
    printf("Enter the number of cities: ");
    scanf("%d", &numCities);
    numEdges = numCities - 1;
    Graph* graph = createGraph(numCities, numEdges);
    printf("Enter the cost of connecting the cities:\n");
    for (int i = 0; i < numEdges; i++) {
        printf("Enter the cost of connecting city %d and city %d: ", i, i +
1);
        scanf("%d", &(graph->edges[i].weight));
        graph->edges[i].src = i;
        graph->edges[i].dest = i + 1;
    }
    kruskalMST(graph);
    return 0;
}
OUTPUT
PROGRAM-3

3. Assume that same road construction project is given to another person. The
amount he will earn from this project is directly proportional to the budget of
the project. This person is greedy, so he decided to maximize the budget by
constructing those roads who have highest construction cost. Design an
algorithm and implement it using a program to find the maximum budget
required for the project.

SOURCE CODE

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#define MAX_VERTICES 100
#define MAX_EDGES (MAX_VERTICES * (MAX_VERTICES - 1) / 2)
typedef struct Edge
{
int source, destination, weight;
} Edge;
int compareEdges(const void *a, const void *b)
{
Edge *edgeA = (Edge *)a;
Edge *edgeB = (Edge *)b;
return edgeB->weight - edgeA->weight;
}
int findParent(int parent[], int vertex)
{
if (parent[vertex] != vertex)
parent[vertex] = findParent(parent, parent[vertex]);
return parent[vertex];
}
void unionSubsets(int parent[], int rank[], int x, int y)
{
int xroot = findParent(parent, x);
int yroot = findParent(parent, y);
if (rank[xroot] < rank[yroot])
parent[xroot] = yroot; else if
(rank[xroot] > rank[yroot])
parent[yroot] = xroot;
else
{
parent[yroot] = xroot;
rank[xroot]++;
}
}
int kruskalMaximumSpanningWeight(Edge edges[], int V, int E)
{
Edge mst[MAX_EDGES];
int parent[MAX_VERTICES];
int rank[MAX_VERTICES];
qsort(edges, E,sizeof(Edge), compareEdges);
for (int i = 0; i < V; i++)
{
parent[i] = i;
rank[i] = 0;
}
int mstIndex = 0;
for (int i = 0; i < E; i++)
{
Edge currentEdge = edges[i];
int x = findParent(parent, currentEdge.source);
int y = findParent(parent, currentEdge.destination);
if (x != y)
{
mst[mstIndex++] = currentEdge;
unionSubsets(parent, rank, x, y);
}
}
int maximumSpanningWeight = 0;
for (int i = 0; i < mstIndex; i++)
maximumSpanningWeight += mst[i].weight;
return maximumSpanningWeight;
}
int main()
{
int V;
printf("Enter the number of vertices in the graph: ");
scanf("%d", &V);
int graph[MAX_VERTICES][MAX_VERTICES];
printf("Enter the cost adjacency matrix:\n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
scanf("%d", &graph[i][j]);
}
}
Edge edges[MAX_EDGES];
int edgeCount = 0;
for (int i = 0; i < V; i++)
{
for (int j = i + 1; j < V; j++)
{
if (graph[i][j] != 0)
{
edges[edgeCount].source = i;
edges[edgeCount].destination = j;
edges[edgeCount].weight = graph[i][j];
edgeCount++;
}
}
}
int maximumSpanningWeight = kruskalMaximumSpanningWeight(edges, V, edgeCount);
printf("Maximum spanning weight: %d\n", maximumSpanningWeight);
return 0;
}

OUTPUT
WEEK:9 PROGRAM-1

1. Given a graph, Design an algorithm and implement it using a


program to implement Floyd Warshall all pair shortest path algorithm.

SOURCE CODE
#include <stdio.h>
#define nV 5
#define INF 999
void printMatrix(int matrix[][nV]);
void floydWarshall(int graph[][nV]) {
int matrix[nV][nV], i, j, k;
for (i = 0; i < nV;i++)
for (j = 0; j < nV; j++) matrix[i][j] =graph[i][j];
 for (k = 0; k < nV; k++)
 {
    for(i =0; i < nV; i++)
    {
        for (j = 0; j < nV; j++)
     {
      if (matrix[i][k] + matrix[k][j] < matrix[i][j])
      matrix[i][j] = matrix[i][k] + matrix[k][j];
     }
    }
 }
printMatrix(matrix);
}
void printMatrix(int matrix[][nV]) {

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


for (int j = 0; j < nV; j++) {
if (matrix[i][j] == INF)
printf("%5s", "INF");
else
printf("%5d", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int graph[nV][nV] = {{0, 10, 5, 5, INF,},
{INF, 0, 5, 5, 5},
{INF, INF, 0, INF, 10},
{INF, INF, INF, 0, 20},
{INF, INF, INF, 5, 0}};
floydWarshall(graph);
}
OUTPUT
PROGRAM-2

2. Given a knapsack of maximum capacity w. N items are provided, each having its own
value and weight. You have to Design an algorithm and implement it using a program
to find the list of the selected items such that the final selected content has weight w and
has maximum value. You can take fractions of items ,i.e. the items can be broken into
smaller pieces so that you have to carry only a fraction xi of item i, where 0 ≤xi≤ 1.

SOURCE CODE

#include <stdio.h>
#include <stdlib.h>
struct Item {
    int weight;
    int value;
};
int compare(const void *a, const void *b) {
    struct Item *itemA = (struct Item *)a;
    struct Item *itemB = (struct Item *)b;
    double ratioA = (double)itemA->value / itemA->weight;
    double ratioB = (double)itemB->value / itemB->weight;
    if (ratioA > ratioB)
        return -1;
    else if (ratioA < ratioB)
        return 1;
    else
        return 0;
}
double fractionalKnapsack(int capacity, struct Item items[], int N) {
    qsort(items, N, sizeof(struct Item), compare);

    double totalValue = 0.0;


    int currentWeight = 0;

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


        if (currentWeight + items[i].weight <= capacity) {
            currentWeight += items[i].weight;
            totalValue += items[i].value;
        } else {
            int remainingWeight = capacity - currentWeight;
            double fraction = (double)remainingWeight / items[i].weight;
            totalValue += fraction * items[i].value;
            break;
        }
    }

    return totalValue;
}
int main() {
    int N;
    printf("Enter the number of items: ");
    scanf("%d", &N);

    struct Item items[N];


    printf("Enter the weights of the items: ");
    for (int i = 0; i < N; i++) {
        scanf("%d", &items[i].weight);
    }

    printf("Enter the values of the items: ");


    for (int i = 0; i < N; i++) {
        scanf("%d", &items[i].value);
    }

    int capacity;
    printf("Enter the maximum capacity of the knapsack: ");
    scanf("%d", &capacity);

    double maxValue = fractionalKnapsack(capacity, items, N);


    printf("Maximum value obtainable = %.2f\n", maxValue);

    return 0;
}

OUTPUT
PROGRAM-3

3. Given an array of elements. Assume arr[i] represents the size of file i. Write an
algorithm and a program to merge all these files into single file with minimum
computation. For given two files A and B with sizes m and n, computation cost of
merging them is O(m+n). (Hint: use greedy approach)

SOURCE CODE
#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {


    int* intA = (int*)a;
    int* intB = (int*)b;

    return (*intA - *intB);


}

int mergeFiles(int arr[], int n) {


    qsort(arr, n, sizeof(int), compare);

    int cost = 0;
    int i = 0;

    while (i < n - 1) {
        int file1 = arr[i];
        int file2 = arr[i + 1];
        int mergedFile = file1 + file2;

        cost += mergedFile;

        arr[i + 1] = mergedFile;
        i++;
    }

    return cost;
}

int main() {
    int n;
    printf("Enter the size of array: ");
    scanf("%d", &n);

    int arr[n];
   
    printf("Enter the elements of array: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int cost = mergeFiles(arr, n);


    printf("%d\n", cost);

    return 0;
}

OUTPUT
PROGRAM-1
1. After end term examination, Akshay wants to party with his friends. All his friends are living
as paying guest and it has been decided to first gather at Akshay’s house and then move
towards party location. The problem is that no one knows the exact address of his house in the
city. Akshay as a computer science wizard knows how to apply his theory subjects in his real life
and came up with an amazing idea to help his friends. He draws a graph by looking in to
location of his house and his friends’ location (as a node in the graph) on a map. He wishes to
find out shortest distance and path covering that distance from each of his friend’s location to
his house and then whatsapp them this path so that they can reach his house in minimum time.
Akshay has developed the program that implements Dijkstra’s algorithm but not sure about
correctness of results. Can you also implement the same algorithm and verify the correctness of
Akshay’s results? (Hint: Print shortest path and distance from friends’ location to Akshay’s
house).

SOURCE CODE
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_NODES 100
typedef struct { int distance; int visited;
int previous;
} Node;
int minDistance(Node dist[], int n) {
int min = INT_MAX, minIndex;
for (int i = 0; i < n; i++) {
if (!dist[i].visited && dist[i].distance <= min) {
min = dist[i].distance; minIndex = i;
}
}
return minIndex;
}
printPath(int parent[], int j) {
if (parent[j] == -1) {
printf("%d ", j);
return;
}
printPath(parent, parent[j]);
printf("%d ", j);
}
void printSolution(Node nodes[], int parent[], int startNode, int n) {
for (int i = 0; i < n; i++) { if (i != startNode) {
printf("Shortest distance from Friends to Akshay's house: %d\n",
nodes[i].distance);
printPath(parent, i);
printf("\n\n");
}
}
}
void dijkstra(int graph[MAX_NODES][MAX_NODES], int startNode, int n) {
Node nodes[MAX_NODES];
int parent[MAX_NODES];
for (int i = 0; i < n; i++) {
nodes[i].distance = INT_MAX;
nodes[i].visited = 0;
nodes[i].previous = -1;
}
nodes[startNode].distance = 0;
for (int count = 0; count < n - 1; count++) {
int u = minDistance(nodes, n);
nodes[u].visited = 1;
for (int v = 0; v < n; v++) {
if (!nodes[v].visited && graph[u][v] && nodes[u].distance != INT_MAX &&
nodes[u].distance + graph[u][v] < nodes[v].distance)
{
nodes[v].distance = nodes[u].distance + graph[u][v];
parent[v] = u;
}
}
}
printSolution(nodes, parent,startNode, n);
}
int main() {
int graph[MAX_NODES][MAX_NODES] = {
{0, 4, 1, 0, 0},
{0, 0, 0, 0, 4},
{0, 2, 0, 4, 0},
{0, 0, 0, 0, 4},
{0, 0, 0, 0, 0}
};
int numNodes = 5;
int akshayHouse = 0;
dijkstra(graph, akshayHouse, numNodes);
return 0;
}

OUTPUT

You might also like