TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
longest_increasing_subsequence.cpp
Go to the documentation of this file.
1
22
#include <cassert>
23
#include <climits>
24
#include <cstdint>
25
#include <iostream>
26
#include <vector>
27
32
namespace
dynamic_programming
{
40
uint64_t
LIS
(
const
std::vector<uint64_t> &a,
const
uint32_t &n) {
41
std::vector<int> lis(n);
42
for
(
int
i = 0; i < n; ++i) {
43
lis[i] = 1;
44
}
45
for
(
int
i = 0; i < n; ++i) {
46
for
(
int
j = 0; j < i; ++j) {
47
if
(a[i] > a[j] && lis[i] < lis[j] + 1) {
48
lis[i] = lis[j] + 1;
49
}
50
}
51
}
52
int
res = 0;
53
for
(
int
i = 0; i < n; ++i) {
54
res = std::max(res, lis[i]);
55
}
56
return
res;
57
}
58
}
// namespace dynamic_programming
59
64
static
void
test
() {
65
std::vector<uint64_t> a = {15, 21, 2, 3, 4, 5, 8, 4, 1, 1};
66
uint32_t n = a.size();
67
68
uint32_t result =
dynamic_programming::LIS
(a, n);
69
assert(result ==
70
5);
71
72
std::cout <<
"Self-test implementations passed!"
<< std::endl;
73
}
74
81
int
main
(
int
argc,
char
const
*argv[]) {
82
uint32_t n = 0;
83
84
std::cout <<
"Enter size of array: "
;
85
std::cin >> n;
86
87
std::vector<uint64_t> a(n);
88
89
std::cout <<
"Enter array elements: "
;
90
for
(
int
i = 0; i < n; ++i) {
91
std::cin >> a[i];
92
}
93
94
std::cout <<
"\nThe result is: "
<<
dynamic_programming::LIS
(a, n)
95
<< std::endl;
96
test
();
// run self-test implementations
97
98
return
0;
99
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
test
static void test()
Self-test implementations.
Definition
longest_increasing_subsequence.cpp:64
dynamic_programming
Dynamic Programming algorithms.
dynamic_programming::LIS
uint64_t LIS(const std::vector< uint64_t > &a, const uint32_t &n)
Calculate the longest increasing subsequence for the specified numbers.
Definition
longest_increasing_subsequence.cpp:40
dynamic_programming
longest_increasing_subsequence.cpp
Generated by
1.12.0