Skip to content

Commit 04236d1

Browse files
committed
2 parents 5e29351 + da22899 commit 04236d1

File tree

11 files changed

+373
-2
lines changed

11 files changed

+373
-2
lines changed

CONTRIBUTORS.md

+4-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ Thanks for all your contributions :heart: :octocat:
66

77

88
[prateekiiest](https://github.com/prateekiiest) : KWOC Mentor
9-
109
| Github username | Pull Request | Status |
11-
| Ankitr19(https://github.com/Ankitr19) | |https://github.com/codeIIEST/Algorithms/pull/203| |Open|
10+
|[Ankitr19](https://github.com/Ankitr19)| [#203]https://github.com/codeIIEST/Algorithms/pull/203 |OPEN|
11+
|[Rahul Arulkumaran](https://github.com/rahulkumaran)| [#46](https://github.com/codeIIEST/Algorithms/pull/46), [#66](https://github.com/codeIIEST/Algorithms/pull/66), [#88](https://github.com/codeIIEST/Algorithms/pull/88), [#89](https://github.com/codeIIEST/Algorithms/pull/89), [#90](https://github.com/codeIIEST/Algorithms/pull/90), [#93](https://github.com/codeIIEST/Algorithms/pull/93), [#159](https://github.com/codeIIEST/Algorithms/pull/159) | CLOSED |
12+
|[Rahul Arulkumaran](https://github.com/rahulkumaran)| [#94](https://github.com/codeIIEST/Algorithms/pull/94), [#95](https://github.com/codeIIEST/Algorithms/pull/95), [#112](https://github.com/codeIIEST/Algorithms/pull/112), [#151](https://github.com/codeIIEST/Algorithms/pull/151), [#174](https://github.com/codeIIEST/Algorithms/pull/174) | MERGED |
13+
|[Rahul Arulkumaran](https://github.com/rahulkumaran)| [#206](https://github.com/codeIIEST/Algorithms/pull/206), [#207](https://github.com/codeIIEST/Algorithms/pull/207) | OPEN |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)
2+
3+
length | 1 2 3 4 5 6 7 8
4+
--------------------------------------------
5+
price | 1 5 8 9 10 17 17 20
6+
7+
1) Optimal Substructure:
8+
We can get the best price by making a cut at different positions and comparing the values obtained after a cut. We can recursively call the same function for a piece obtained after a cut.
9+
10+
Let cutRoad(n) be the required (best possible price) value for a rod of lenght n. cutRod(n) can be written as following.
11+
12+
cutRod(n) = max(price[i] + cutRod(n-i-1)) for all i in {0, 1 .. n-1}
13+
14+
2) Overlapping Subproblems
15+
Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array val[] in bottom up manner.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include<stdio.h>
2+
#include<limits.h>
3+
4+
// A utility function to get the maximum of two integers
5+
int max(int a, int b)
6+
{
7+
return (a > b)? a : b;
8+
}
9+
10+
11+
/* Returns the best obtainable price for a rod of length n and
12+
price[] as prices of different pieces */
13+
int DPcutRod(int price[], int n)
14+
{
15+
int val[n+1];
16+
val[0] = 0;
17+
int i, j;
18+
for (i = 1; i<=n; i++)
19+
{
20+
int max_val = INT_MIN;
21+
// Recursively cut the rod in different pieces and compare different
22+
// configurations
23+
for (j = 0; j < i; j++)
24+
max_val = max(max_val, price[j] + val[i-j-1]);
25+
val[i] = max_val;
26+
}
27+
return val[n];
28+
}
29+
30+
int main()
31+
{
32+
int n;
33+
printf("Enter rod length\n");
34+
scanf("%d",&n);
35+
int arr[n],i;
36+
printf("Enter prices for lengths 1 to n\n");
37+
for(i=0;i<n;i++)
38+
{
39+
scanf("%d",&arr[i]);
40+
}
41+
printf("Maximum Obtainable Value is %d\n", DPcutRod(arr, n));
42+
getchar();
43+
return 0;
44+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1) and (i+1, j+1) can be traversed.
2+
3+
1) Optimal Substructure
4+
The path to reach (m, n) must be through one of the 3 cells: (m-1, n-1) or (m-1, n) or (m, n-1). So minimum cost to reach (m, n) can be written as “minimum of the 3 cells plus cost[m][n]”.
5+
6+
minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n]
7+
8+
2) Overlapping Subproblems
9+
Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be
10+
avoided by constructing a temporary array tc[][] in bottom up manner.
11+
12+
13+
Example:
14+
3 3
15+
1 2 3
16+
4 8 2
17+
1 5 3
18+
19+
Ouptut:
20+
8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
#include <algorithm>
3+
4+
using namespace std;
5+
6+
int main(){
7+
std::ios::sync_with_stdio(false);
8+
/*
9+
We can easily observe that the optimum solution of the minimum
10+
cost at any row i is only dependent on the cost at row i-1 and
11+
the current row elements. Thus if we only store these two arrays
12+
of length c, We have reduced space from n*m to 2*m.
13+
*/
14+
15+
int i, j, r, c;
16+
printf("Enter no of rows and no of cols\n");
17+
cin>>r>>c; //take input of the rows and columns from user.
18+
int cost[c], dp[c];
19+
int x;
20+
/*
21+
Since for the first row the minimum cost is the only cost possible
22+
required to get there, we directly calculate it.
23+
*/
24+
printf("Enter a R X C array\n");
25+
26+
for(i=0; i<c; i++){
27+
cin>>cost[i];
28+
if(i>0) cost[i] = cost[i] + cost[i-1];
29+
}
30+
/*
31+
For the subsequent rows, the optimised cost for each cell in the
32+
previous row has been stored in the array cost[] and the optimised
33+
cost for the present row is stored in the array dp[].
34+
*/
35+
for(i=1; i<r; i++){
36+
for(j=0; j<c; j++){
37+
cin>>x;
38+
if(j==0)
39+
dp[j] = cost[j] + x;
40+
else{
41+
dp[j] = x + min(dp[j-1], min(cost[j-1], cost[j]));
42+
}
43+
}
44+
/*
45+
After dp[] has been found entirely, we copy its elements to
46+
cost[] and continue the iteration.
47+
*/
48+
for(j=0; (j<c && i!=c-1); j++){
49+
cost[j] = dp[j];
50+
}
51+
}
52+
printf("The min cost path from 1,1 to r,c is\n");
53+
cout<<dp[c-1]<<"\n";
54+
return 0;
55+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.
2+
3+
Examples: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
4+
Output: True //There is a subset (4, 5) with sum 9.
5+
6+
Let isSubSetSum(int set[], int n, int sum) be the function to find whether there is a subset of set[] with sum equal to sum. n is the number of elements in set[].
7+
8+
The isSubsetSum problem can be divided into two subproblems
9+
…a) Include the last element, recur for n = n-1, sum = sum – set[n-1]
10+
…b) Exclude the last element, recur for n = n-1.
11+
If any of the above the above subproblems return true, then return true.
12+
13+
Following is the recursive formula for isSubsetSum() problem.
14+
15+
isSubsetSum(set, n, sum) = isSubsetSum(set, n-1, sum) ||
16+
isSubsetSum(set, n-1, sum-set[n-1])
17+
Base Cases:
18+
isSubsetSum(set, n, sum) = false, if sum > 0 and n == 0
19+
isSubsetSum(set, n, sum) = true, if sum == 0
20+
21+
We can solve the problem in Pseudo-polynomial time using Dynamic programming. We create a boolean 2D table subset[][] and fill it in bottom up manner. The value of subset[i][j] will be true if there is a subset of set[0..j-1] with sum equal to i., otherwise false. Finally, we return subset[sum][n]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <stdio.h>
2+
3+
// Returns true if there is a subset of a[] with sun equal to given sum
4+
bool DP(int set[], int n, int sum)
5+
{
6+
// The value of subset[i][j] will be true if there is a
7+
// subset of set[0..j-1] with sum equal to i
8+
bool subset[n+1][sum+1];
9+
// If sum is 0, then answer is true
10+
for (int i = 0; i <= n; i++)
11+
subset[i][0] = true;
12+
// If sum is not 0 and set is empty, then answer is false
13+
for (int i = 1; i <= sum; i++)
14+
subset[0][i] = false;
15+
// Fill the subset table in botton up manner
16+
for (int i = 1; i <= n; i++)
17+
{
18+
for (int j = 1; j <= sum; j++)
19+
{
20+
if(j<set[i-1])
21+
subset[i][j] = subset[i-1][j];
22+
if (j >= set[i-1])
23+
subset[i][j] = subset[i-1][j] ||
24+
subset[i - 1][j-set[i-1]];
25+
}
26+
}
27+
return subset[n][sum];
28+
}
29+
30+
int main()
31+
{
32+
int n;
33+
int sum;
34+
printf("Enter no of elements of array and desired sum\n");
35+
scanf("%d%d",&n,&sum);
36+
int i,a[n];
37+
printf("Enter the array\n");
38+
for(i=0;i<n;i++)
39+
scanf("%d",&a[i]);
40+
if (DP(a, n+1, sum) == true)
41+
printf("Found a subset with given sum\n");
42+
else
43+
printf("No subset with given sum\n");
44+
return 0;
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, 1 is included.
2+
3+
Given a number n, the task is to find n’th Ugly number.
4+
5+
Input : n = 7
6+
Output : 8
7+
8+
Input : n = 10
9+
Output : 12
10+
11+
Input : n = 15
12+
Output : 24
13+
14+
Input : n = 150
15+
Output : 5832
16+
17+
DP method:
18+
Here is a time efficient solution with O(n) extra space. The ugly-number sequence is 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …
19+
because every number can only be divided by 2, 3, 5, one way to look at the sequence is to split the sequence to three groups as below:
20+
(1) 1×2, 2×2, 3×2, 4×2, 5×2, …
21+
(2) 1×3, 2×3, 3×3, 4×3, 5×3, …
22+
(3) 1×5, 2×5, 3×5, 4×5, 5×5, …
23+
24+
We can find that every subsequence is the ugly-sequence itself (1, 2, 3, 4, 5, …) multiply 2, 3, 5. Then we use similar merge method as merge sort, to get every ugly number from the three subsequence. Every step we choose the smallest one, and move one step after.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
int main()
4+
{
5+
printf("Enter no of test cases\n");
6+
int t; cin >> t;
7+
int i2, i3, i5;
8+
i2 = i3 = i5 = 0;
9+
int ugly[500];// To store ugly numbers
10+
ugly[0] = 1;
11+
for (int i = 1; i < 500; ++i) {
12+
ugly[i] = min(ugly[i2]*2, min(ugly[i3]*3, ugly[i5]*5));//get minimum of possible solutions
13+
ugly[i] != ugly[i2]*2 ? : i2++; // next_mulitple_of_2 = ugly[i2]*2;
14+
ugly[i] != ugly[i3]*3? : i3++; // next_mulitple_of_3 = ugly[i3]*3
15+
ugly[i] != ugly[i5]*5 ? : i5++; // next_mulitple_of_5 = ugly[i5]*5;
16+
}
17+
int n;
18+
while(t--) {
19+
printf("Enter 'n' for the nth ugly number\n");
20+
cin >> n;
21+
cout << ugly[n-1] << endl;
22+
}
23+
return 0;
24+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Z Algorithm
2+
3+
This algorithm finds all occurrences of a pattern in a text in linear time. Let length of text be n and of pattern be m, then total time taken is O(m + n) with linear space complexity. Now we can see that both time and space complexity is same as KMP algorithm but this algorithm is Simpler to understand.
4+
5+
In this algorithm, we construct a Z array.
6+
7+
# What is Z array?
8+
9+
For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself.
10+
Example:
11+
Index 0 1 2 3 4 5 6 7 8 9 10 11
12+
Text a a b c a a b x a a a z
13+
Z values X 1 0 0 3 1 0 0 2 2 1 0
14+
15+
# How to construct Z array?
16+
17+
The idea is to maintain an interval [L, R] which is the interval with max R
18+
such that [L,R] is prefix substring (substring which is also prefix).
19+
20+
Steps for maintaining this interval are as follows –
21+
22+
1) If i > R then there is no prefix substring that starts before i and
23+
ends after i, so we reset L and R and compute new [L,R] by comparing
24+
str[0..] to str[i..] and get Z[i] (= R-L+1).
25+
26+
2) If i <= R then let K = i-L, now Z[i] >= min(Z[K], R-i+1) because
27+
str[i..] matches with str[K..] for atleast R-i+1 characters (they are in
28+
[L,R] interval which we know is a prefix substring).
29+
Now two sub cases arise –
30+
a) If Z[K] < R-i+1 then there is no prefix substring starting at
31+
str[i] (otherwise Z[K] would be larger) so Z[i] = Z[K] and
32+
interval [L,R] remains same.
33+
b) If Z[K] >= R-i+1 then it is possible to extend the [L,R] interval
34+
thus we will set L as i and start matching from str[R] onwards and
35+
get new R then we will update interval [L,R] and calculate Z[i] (=R-L+1)
36+
37+
The algorithm runs in linear time because we never compare character less than R and with matching we increase R by one so there are at most T comparisons. In mismatch case, mismatch happen only once for each i (because of which R stops), that’s another at most T comparison making overall linear complexity.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
4+
#define md 1000000007
5+
#define ll long long int
6+
#define vi vector<int>
7+
#define vll vector<i64>
8+
#define pb push_back
9+
#define all(c) (c).begin(),(c).end()
10+
template< class T > T max2(const T &a,const T &b) {return (a < b ? b : a);}
11+
template< class T > T min2(const T &a,const T &b) {return (a > b ? b : a);}
12+
template< class T > T max3(const T &a, const T &b, const T &c) { return max2(a, max2(b, c)); }
13+
template< class T > T min3(const T &a, const T &b, const T &c) { return min2(a, min2(b, c)); }
14+
template< class T > T gcd(const T a, const T b) { return (b ? gcd<T>(b, a%b) : a); }
15+
template< class T > T lcm(const T a, const T b) { return (a / gcd<T>(a, b) * b); }
16+
template< class T > T mod(const T &a, const T &b) { return (a < b ? a : a % b); }
17+
typedef pair<ll,ll> pi;
18+
int main()
19+
{
20+
fastio;
21+
string txt;
22+
string pat;
23+
getline(cin,txt);//getline() reads the complete line in contrary to the traditional cin function which reads just the string before any spaces
24+
getline(cin,pat);
25+
int n = txt.length();
26+
int pat_len = pat.length();
27+
string str = pat + "$" + txt;//This is the new string that is formed after merging the pattern, '$' and txt string . we can use any other symbol instead of '$'.I have used dollar sign because it occurs rarely in the txt string
28+
29+
int len = n+pat_len +1;//length of the total output string
30+
int z_val[len]={0};
31+
int left =0;//left index of the z box
32+
int right =0;//right index of the z box
33+
int count=0;//count of the match
34+
for(int i=1;i<len;i++)
35+
{
36+
int curr = i;
37+
if(count>1)
38+
{
39+
left =i;
40+
right = i + count-2;
41+
}
42+
43+
44+
if(count<=1)
45+
{
46+
count=0;
47+
for(int j=0;j<curr && j<len;j++)
48+
{
49+
if(str[j]==str[curr])
50+
{
51+
count++;
52+
curr++;
53+
}
54+
else
55+
{
56+
z_val[i]=count;
57+
break;
58+
59+
}
60+
}
61+
}
62+
else
63+
{
64+
for(int j=left;j<=right; j++)
65+
{
66+
if(z_val[j-left]+j<right)//looks for the edge cases when the string index + the assigned z value surpasses the right index..this is not possible.So we need to check the match for given letter saperately.
67+
z_val[j]=z_val[j-left];
68+
else
69+
{
70+
count=0;
71+
i=j-1;
72+
break;
73+
}
74+
}
75+
}
76+
}
77+
for(int i=0;i<len;i++)
78+
{
79+
if(z_val[i]==pat_len)//This indicates the index where the string occurence takes place
80+
cout<<i-pat_len<<endl;
81+
}
82+
83+
84+
}

0 commit comments

Comments
 (0)