-
Notifications
You must be signed in to change notification settings - Fork 0
/
lis.c
71 lines (63 loc) · 1.95 KB
/
lis.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* lis.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nkawaguc <nkawaguc@student.42tokyo.jp> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/14 21:48:18 by nkawaguc #+# #+# */
/* Updated: 2024/10/19 22:55:41 by nkawaguc ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
#include <stdio.h>
static void lis_dp(int *arr, int size, int *dp, int *idx);
static int *lis_traceback(int *arr, int size, int *idx, int lis_size);
int *lis(int *arr, int size, int *lis_size)
{
int *dp;
int *idx;
int *ans;
dp = (int *)malloc(sizeof(int) * size);
idx = (int *)malloc(sizeof(int) * size);
if (dp == NULL || idx == NULL)
error();
lis_dp(arr, size, dp, idx);
*lis_size = lower_bound(dp, size, INF);
ans = lis_traceback(arr, size, idx, *lis_size);
return (free(dp), free(idx), ans);
}
static void lis_dp(int *arr, int size, int *dp, int *idx)
{
int i;
i = -1;
while (++i < size)
{
dp[i] = INF;
idx[i] = -1;
}
i = -1;
while (++i < size)
{
idx[i] = lower_bound(dp, size, arr[i]);
dp[idx[i]] = arr[i];
}
}
static int *lis_traceback(int *arr, int size, int *idx, int lis_size)
{
int *ans;
int i;
int j;
ans = (int *)malloc(sizeof(int) * (size + 1));
if (ans == NULL)
error();
i = -1;
while (++i < size)
ans[i] = INF;
i = lis_size;
j = size;
while (--j >= 0)
if (idx[j] == i - 1)
ans[--i] = arr[j];
return (ans);
}