Skip to content

Commit 3589867

Browse files
Merge pull request matthewsamuel95#82 from aniket7joshi/aniket7joshi_LCIS_CPP
Issue matthewsamuel95#81 lcis resolved
2 parents 87058dc + dbf1e48 commit 3589867

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

DP/LCIS/lcis.cpp

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
// Returns the length and the LCIS of two
5+
// arrays arr1[0..n-1] and arr2[0..m-1] and
6+
// prints LCIS
7+
int LCIS(int arr1[], int n, int arr2[], int m)
8+
{
9+
// table[j] is going to store length of LCIS
10+
// ending with arr2[j]. We initialize it as 0,
11+
int table[m], parent[m];
12+
for (int j=0; j<m; j++)
13+
table[j] = 0;
14+
15+
// Traverse all elements of arr1[]
16+
for (int i=0; i<n; i++)
17+
{
18+
// Initialize current length of LCIS
19+
int current = 0, last = -1;
20+
21+
// For each element of arr1[], trvarse all
22+
// elements of arr2[].
23+
for (int j=0; j<m; j++)
24+
{
25+
// If both the array have same elements.
26+
// Note that we don't break the loop here.
27+
if (arr1[i] == arr2[j])
28+
{
29+
if (current + 1 > table[j])
30+
{
31+
table[j] = current + 1;
32+
parent[j] = last;
33+
}
34+
}
35+
36+
/* Now seek for previous smaller common
37+
element for current element of arr1 */
38+
if (arr1[i] > arr2[j])
39+
{
40+
if (table[j] > current)
41+
{
42+
current = table[j];
43+
last = j;
44+
}
45+
}
46+
}
47+
}
48+
49+
// The maximum value in table[] is out result
50+
int result = 0, index = -1;
51+
for (int i=0; i<m; i++)
52+
{
53+
if (table[i] > result)
54+
{
55+
result = table[i];
56+
index = i;
57+
}
58+
}
59+
60+
// LCIS is going to store elements of LCIS
61+
int lcis[result];
62+
for (int i=0; index != -1; i++)
63+
{
64+
lcis[i] = arr2[index];
65+
index = parent[index];
66+
}
67+
68+
cout << "The LCIS is : ";
69+
for (int i=result-1; i>=0; i--)
70+
printf ("%d ", lcis[i]);
71+
72+
return result;
73+
}
74+
75+
/* Driver program to test above function */
76+
int main()
77+
{
78+
int arr1[1000];
79+
int arr2[1000];
80+
int n,m;
81+
printf("Enter size of 2 arrays");
82+
scanf("%d%d",&n,&m);
83+
printf("Enter 1st array\n");
84+
for(int i = 0;i<n;i++)
85+
{
86+
scanf("%d",&arr1[i]);
87+
}
88+
printf("Enter 2nd array\n");
89+
for(int i = 0;i<m;i++)
90+
{
91+
scanf("%d",&arr2[i]);
92+
}
93+
cout << "\nLength of LCIS is "
94+
<< LCIS(arr1, n, arr2, m);
95+
return (0);
96+
}

LCIS/a.out

13.1 KB
Binary file not shown.

0 commit comments

Comments
 (0)