0% found this document useful (0 votes)
36 views7 pages

Max Sub Array:: Using Namespace Int Int Int Int Int Int Int Int

The document discusses several algorithms including maximum subarray, karatsuba multiplication, fractional knapsack, longest common subsequence, matrix chain multiplication, naive string matching, Knuth-Morris-Pratt algorithm, assembly line scheduling, 0-1 knapsack, Huffman coding, Rabin-Karp algorithm. Code implementations are provided for each algorithm discussed.

Uploaded by

Arth Agrawal
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)
36 views7 pages

Max Sub Array:: Using Namespace Int Int Int Int Int Int Int Int

The document discusses several algorithms including maximum subarray, karatsuba multiplication, fractional knapsack, longest common subsequence, matrix chain multiplication, naive string matching, Knuth-Morris-Pratt algorithm, assembly line scheduling, 0-1 knapsack, Huffman coding, Rabin-Karp algorithm. Code implementations are provided for each algorithm discussed.

Uploaded by

Arth Agrawal
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/ 7

Max Sub array:

#include<iostream>
#include<algorithm>
using namespace std;

int css(int a[], int low, int mid, int high){


int sum=0;
int lsum=-999;
for(int i=mid; i>=low; i--){
sum+=a[i];
if (sum>lsum){
lsum=sum;
}
else{
break;
}
}

sum = 0;
int rsum=-999;
for(int i=mid+1; i<=high; i++){
sum+=a[i];
if(sum>rsum){
rsum=sum;
}
else{
break;
}
}
return (lsum+rsum);
}
int mss(int a[], int low, int high) {
int mid=0, leftsum=0, rightsum=0, crosssum=0;
if (high==low){
return a[low];
}
else{
mid=(high+low)/2;
leftsum = mss(a, low, mid);
rightsum = mss(a, mid+1, high);
crosssum = css(a, low, mid, high);
}
int ret = max({leftsum, rightsum, crosssum});
return ret;
}
int main(){
int n=0;
cout<<"Enter number of elements:";
cin>>n;
int a[n];
cout<<"Enter elements:";
for(int i=0; i<n; i++){
cin>>a[i];
}
int sum=mss(a, 0, n-1);
cout<<sum;
return 0;
}
Karatsuba Algorithm:
x = int(input())
y = int(input())

def karatsuba(x,y):
if x<10 or y<10:
return x*y
else:
n = max(len(str(x)),len(str(y)))
half=n//2
a = x//(10**(half))
b = x%(10**(half))
c = y//(10**(half))
d = y%(10**(half))

ac = karatsuba(a,c)
bd = karatsuba(b,d)
ad_plus_bc = karatsuba(a+b,c+d)-ac-bd
return ac*(10**(2*(half))) + (ad_plus_bc*(10**half)) + bd

print(karatsuba(x,y))

Fractional Knapsack:
#include <iostream>
#include <vector>
using namespace std;

void swapValues(double &a, double &b) {


double temp = a;
a = b;
b = temp;
}
double knapsack(double profits[], double weights[], double capacity, int size) {
double ratios[size];
for (int i = 0; i < size; i++) {
ratios[i] = profits[i] / weights[i];
}
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (ratios[j] < ratios[j + 1]) {
swapValues(ratios[j], ratios[j+1]);
swapValues(profits[j], profits[j+1]);
swapValues(weights[j], weights[j+1]);
}
}
}
int currentIndex = 0;
double totalProfit = 0;
vector<double> selectedWeights;
while(true) {
if(capacity - weights[currentIndex] >= 0) {
capacity -= weights[currentIndex];
totalProfit += profits[currentIndex];
selectedWeights.push_back(weights[currentIndex]);
currentIndex++;
}
else {
break;
}
}
double remainingCapacityWeightRatio = capacity * ratios[currentIndex];
totalProfit += remainingCapacityWeightRatio;
return totalProfit;
}
int main() {
int numItems;
cin >> numItems;
double itemProfits[numItems];
double itemWeights[numItems];
for(int i = 0; i < numItems; i++) {
cin >> itemWeights[i];
}
for(int j = 0; j < numItems; j++) {
cin >> itemProfits[j];
}
double knapsackCapacity;
cin >> knapsackCapacity;
cout << knapsack(itemProfits, itemWeights, knapsackCapacity, numItems);
return 0;
}

LCS:
#include <bits/stdc++.h>
using namespace std;

int lcs(string X, string Y, int m, int n) {


if (m == 0 || n == 0)
return 0;
if (X[m - 1] == Y[n - 1])
return 1 + lcs(X, Y, m - 1, n - 1);
return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
}
bool isEmbedded(string X, string Y) {
int m = X.size();
int n = Y.size();
int lengthOfLCS = lcs(X, Y, m, n);
return lengthOfLCS == m;
}
int main() {
string S1, S2;
cin >> S1;
cin >> S2;
if (isEmbedded(S1, S2)) {
cout << "YES\n";
} else {
cout << "NO\n";
}
return 0;
}

Matrix chain multiplication:


#include <bits/stdc++.h>
using namespace std;

int MCM(int p[], int i, int j) {


if (i == j) {
return 0;
}
int k;
int mini = INT_MAX;
int count;
for (k = i; k < j; k++) {
count = (MCM(p, i, k) + MCM(p, k + 1, j) + p[i - 1] * p[k] * p[j]);
mini = min(count, mini);
}
return mini;
}
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << MCM(arr, 1, n - 1);
return 0;
}
Naive string matching:

def naivematchstring(x, y):


s = []
for i in range(len(x) - len(y) + 1):
j = 0
while j < len(y) and x[i + j] == y[j]:
j += 1
if j == len(y):
s.append(i)
if len(s) == 0:
return -1
return s

x = input("Enter text: ")


y = input("Enter pattern: ")
print(naivematchstring(x, y))

KMP:

#include <iostream>
#include <vector>
#include <string>

std::vector<int> compute_lps_array(const std::string& pattern) {


int length = 0;
std::vector<int> lps(pattern.size(), 0);
int i = 1;
while (i < pattern.size()) {
if (pattern[i] == pattern[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
std::vector<int> kmp(const std::string& text, const std::string& pattern) {
if (text.empty() || pattern.empty()) {
return {-1};
}
std::vector<int> lps = compute_lps_array(pattern);
int i = 0, j = 0;
std::vector<int> indices;
while (i < text.size()) {
if (pattern[j] == text[i]) {
i++;
j++;
}
if (j == pattern.size()) {
indices.push_back(i - j);
j = lps[j - 1];
} else if (i < text.size() && pattern[j] != text[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
if (indices.empty()) {
return {-1};
}
return indices;
}
int main() {
std::string text, pattern;
std::cin >> text >> pattern;
std::vector<int> indices = kmp(text, pattern);
if (indices[0] == -1) {
std::cout << -1 << std::endl;
} else {
for (int i = 0; i < indices.size(); i++) {
std::cout << indices[i];
if (i != indices.size() - 1) {
std::cout << ",";
}
}
std::cout << std::endl;
}
return 0;
}

Assembly Line Scheduling:


def assembly_line_scheduling(a, t, e, x):
n = len(a[0])

f1 = [0] * n
f2 = [0] * n

f1[0] = e[0] + a[0][0]


f2[0] = e[1] + a[1][0]

for i in range(1, n):


f1[i] = min(f1[i-1] + a[0][i], f2[i-1] + t[1][i] + a[0][i])
f2[i] = min(f2[i-1] + a[1][i], f1[i-1] + t[0][i] + a[1][i])

return min(f1[n-1] + x[0], f2[n-1] + x[1])

a = [[7, 9, 3, 4, 8, 4],
[8, 5, 6, 4, 5, 7]]
t = [[2, 3, 1, 3, 4],
[2, 1, 2, 2, 1]]
e = [2, 3]
x = [3, 2]
print("Fastest time:", assembly_line_scheduling(a, t, e, x))

0-1 Knapsack:

def knapsack(weights, values, capacity):


n = len(weights)

dp = [[0] * (capacity + 1) for _ in range(n + 1)]

for i in range(1, n + 1):


for w in range(1, capacity + 1):
if weights[i - 1] > w:
dp[i][w] = dp[i - 1][w]
else:
dp[i][w] = max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]])

return dp[n][capacity]

weights = [2, 3, 4, 5]
values = [3, 4, 5, 6]
capacity = 5
print("Maximum value:", knapsack(weights, values, capacity))
Huffman Coding:

from heapq import heappush, heappop, heapify


from collections import defaultdict

class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def build_huffman_tree(text):
freq = defaultdict(int)
for char in text:
freq[char] += 1
pq = []
for char, f in freq.items():
node = HuffmanNode(char, f)
heappush(pq, node)
while len(pq) > 1:
left = heappop(pq)
right = heappop(pq)
merge_node = HuffmanNode(None, left.freq + right.freq)
merge_node.left = left
merge_node.right = right
heappush(pq, merge_node)
return pq[0]
def encode_huffman(root, prefix="", code={}):
if root is not None:
if root.char is not None:
code[root.char] = prefix
encode_huffman(root.left, prefix + "0", code)
encode_huffman(root.right, prefix + "1", code)
return code
def huffman_encoding(text):
if not text:
return None, None

root = build_huffman_tree(text)
code = encode_huffman(root)
encoded_text = ''.join(code[char] for char in text)
return encoded_text, root
def huffman_decoding(encoded_text, root):
decoded_text = ""
current_node = root
for bit in encoded_text:
if bit == '0':
current_node = current_node.left
else:
current_node = current_node.right
if current_node.char is not None:
decoded_text += current_node.char
current_node = root
return decoded_text
text = "this is an example for huffman encoding"
encoded_text, tree = huffman_encoding(text)
print("Encoded text:", encoded_text)
decoded_text = huffman_decoding(encoded_text, tree)
print("Decoded text:", decoded_text)
Rabin Karp:

def rabin_karp(pattern, text):


m = len(pattern)
n = len(text)
prime = 101
modulus = 10**9 + 7

def hash_string(s):
h = 0
for char in s:
h = (h * prime + ord(char)) % modulus
return h

pattern_hash = hash_string(pattern)
text_hash = hash_string(text[:m])

for i in range(n - m + 1):


if pattern_hash == text_hash:
if pattern == text[i:i+m]:
return i
if i < n - m:
text_hash = (text_hash - ord(text[i]) * pow(prime, m - 1, modulus)) % modulus
text_hash = (text_hash * prime + ord(text[i + m])) % modulus
text_hash = (text_hash + modulus) % modulus

return -1

pattern = "abc"
text = "ababcabcabababd"
result = rabin_karp(pattern, text)
if result != -1:
print("Pattern found at index:", result)
else:
print("Pattern not found in the text.")

You might also like