Docsity

Longest Increasing Subsequence - C plus plus Code, Study Guides, Projects, Research of Computer Programming

Toggle sidebar
bg1
#include<stdio.h>
#define MAXN 100
int A[MAXN], N;
int L[MAXN], P[MAXN];
void printPath(int x) {
if(P[x] == -1) {
printf("%d",x);
return;
}
printPath(P[x]);
printf(" %d",x);
}
int doLIS() {
int i, j;
int longest = 0, last = 0;
for(i = 1; i<=N; i++) {
int max = 0;
int parent = -1;
for(j = i-1; j>=0; j--) {
if(A[i] > A[j]) {
if(L[j] > max) {
max = L[j];
parent = j;
}
}
}
L[i] = max+1;
P[i] = parent;
if(L[i] > longest) {
longest = L[i];
last = i;
}
}
printf("LIS : ");
printPath(last);
puts("");
printf("Length: %d\n",longest);
return longest;
}
int main() {
int i;
while(scanf("%d",&N) == 1) {
A[0] = 0;
for(i = 1; i<= N; i++) {
scanf("%d",&A[i]);
}
doLIS();
}
return 0;
}๎˜ƒ
docsity.com

Partial preview of the text

Download Longest Increasing Subsequence - C plus plus Code and more Study Guides, Projects, Research Computer Programming in PDF only on Docsity!

#include<stdio.h> #define MAXN 100

int A[MAXN], N; int L[MAXN], P[MAXN];

void printPath(int x) { if(P[x] == -1) { printf("%d",x); return; } printPath(P[x]); printf(" %d",x); }

int doLIS() { int i, j; int longest = 0, last = 0; for(i = 1; i<=N; i++) { int max = 0; int parent = -1; for(j = i-1; j>=0; j--) { if(A[i] > A[j]) { if(L[j] > max) { max = L[j]; parent = j; } } } L[i] = max+1; P[i] = parent; if(L[i] > longest) { longest = L[i]; last = i; } } printf("LIS : "); printPath(last); puts(""); printf("Length: %d\n",longest); return longest; }

int main() { int i; while(scanf("%d",&N) == 1) { A[0] = 0; for(i = 1; i<= N; i++) { scanf("%d",&A[i]); } doLIS();

return 0; }

docsity.com