0% found this document useful (0 votes)
7 views5 pages

Ex No - 11

The document outlines the implementation of approximation algorithms for solving the 0/1 Knapsack Problem and the Travelling Salesman Problem (TSP). It provides the aims, algorithms, and code for both problems, demonstrating how to achieve near-optimal solutions efficiently. The results confirm the successful application of these approximation algorithms.

Uploaded by

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

Ex No - 11

The document outlines the implementation of approximation algorithms for solving the 0/1 Knapsack Problem and the Travelling Salesman Problem (TSP). It provides the aims, algorithms, and code for both problems, demonstrating how to achieve near-optimal solutions efficiently. The results confirm the successful application of these approximation algorithms.

Uploaded by

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

Ex No: 11 Vutukuru

Likitha
3122235002067

Implementation of approximation
algorithms for knapsack and TSP
problems
Approximation Algorithm for Knapsack Problem:
AIM:
The aim is to solve the 0/1 Knapsack Problem using an Approximation
Algorithm, which provides a fast and near-optimal solution instead of an
exact one.

ALGORITHM:
1. Sort items by value-to-weight ratio in descending order.
2. Iterate through the sorted items:
o If the item fits completely, add it to the knapsack.
o If it does not fit, skip it (since it's 0/1 Knapsack).
3. Return the total value obtained.

CODE:
def knapsack_approx():
n = int(input("Enter number of items: "))
capacity = int(input("Enter knapsack capacity: "))
weights = list(map(int, input("Enter weights (space-separated):
").split())) values = list(map(int, input("Enter values (space-
separated): ").split()))
items = sorted(zip(weights, values), key=lambda x: x[1]/x[0],
reverse=True) total_weight = 0
total_value = 0

for w, v in items:
if total_weight + w <= capacity:
total_weight += w
total_value += v
print(f"\nApproximate Maximum Value: {total_value}")
knapsack_approx()

OUTPUT:

RESULT:
Thus the knapsack problem has been successfully solved using
approximation algorithms.

Approximation Algorithm for Travelling Salesman


Problem:
AIM:
The aim is to solve the Travelling Salesman Problem (TSP) using an
Approximation Algorithm, specifically the Nearest Neighbor Heuristic, to find a
near- optimal solution efficiently.

ALGORITHM:
1. Start from any random city (default: City 0).
2. Find the nearest unvisited city and travel there.
3. Repeat until all cities are visited.
4. Return to the starting city to complete the tour.
5. Calculate the total distance of the tour.
CODE:
def tsp_approx():
n = int(input("Enter number of
cities: ")) graph = []
print("Enter cost matrix (space-separated, 0 for
self):") for i in range(n):
row = list(map(int, input(f"Row {i+1}: ").split()))
graph.append(row)
visited = [False] * n
path = [0] # Start at city 1 (index 0)
visited[0] = True
total_cost = 0
for _ in range(n - 1):
curr = path[-1]
next_city =
-1
min_cost = float('inf')
for j in range(n):
if not visited[j] and graph[curr][j] < min_cost:
min_cost = graph[curr][j]
next_city = j
path.append(next_city)
visited[next_city] =
True total_cost +=
min_cost
total_cost += graph[path[-1]][0] # Return to start
print("\nApproximate TSP Path (1-based):", " -> ".join(str(x+1) for x in path), "-
> 1") print(f"Approximate Cost: {total_cost}")
tsp_approx()
OUTPUT:

RESULT:
Thus the travelling salesman problem has been successfully solved
using approximation algorithm .

You might also like