Ex No - 11
Ex No - 11
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.
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 .