# Cod sursa(job #250915)

Utilizator Data 1 februarie 2009 11:58:20 Subsir crescator maximal 0 c done Arhiva educationala 1.91 kb
``````#include <stdio.h>
#include <stdlib.h>
#define MAX 100000

long *lis(long a[], long n, long *z)
{
long i, j, max, *v, *M, *P, *B, m , l, pmax;

M = (long *)malloc(n * sizeof(long));
P = (long *)malloc(n * sizeof(long));
B = (long *)malloc(n * sizeof(long));
//process the matrix
max = 0;
pmax = 1;
for (i = 0; i < n; i++)
{
//binary search.
m = 0;
l = max;
j = (l + 1)/ 2;
while (j <= l)
{
printf("M[%ld] = %ld\n", j, M[j]);
printf("M[%ld] = %ld\n", j + 1, M[j+1]);
if (a[M[j]] < a[i] && a[M[j+1]] >= a[i]) break;
if (a[M[j]] < a[i])
{
m = j + 1;
}
else
{
l = j - 1;
}
j = (m + l + 1) / 2 ;

}
printf("j = %ld\n", j);
//check if
if (j == 0)
{
P[i] = -1;
B[i] = 1;

}
else
{
P[i] = M[j];
B[i] = B[M[j]] + 1;
}
if (j == max || a[i] < a[M[j + 1]])
{
M[j+1] = i;
printf("M[%ld] = %ld\n", j + 1, M[j+1]);
if (max < j+1)
{
max = j + 1;
B[i] = max;
pmax = i;
}
}
printf("max = %ld\n", max);
}
*z = max;
v = (long *)malloc(max * sizeof(long));
printf("max %ld\n", max);
for (i = 0; i < n; i++)
printf("M = %ld P=%ld B=%ld\n", M[i], P[i], B[i]);
printf("\n");
while (max > 0)
{
v[max-1] = pmax;
max--;
pmax = P[pmax];
}
for (i = 0; i < *z; i++)
printf("%ld ", v[i]);
printf("\n");
return v;
}

int main()
{
long a[MAX], n, i, *rez, z;
FILE *fin, *fout;

if ((fin = fopen("scmax.in", "r")) == NULL)
{
printf("Eroare \n");
exit(-1);
}
fscanf(fin, "%ld", &n);

for (i = 0; i<n ; i++)
fscanf(fin, "%ld", &a[i]);
/*
for (i = 0; i < m; i++)
prlongf("%d ", a[i]);
prlongf("\n");
for (i = 0; i < n; i++)
prlongf("%d ", b[i]);
prlongf("\n");
*/	rez = lis(a,n,&z);

fout = fopen("scmax.out", "w");
fprintf(fout, "%ld\n", z);
if (z != 0)
{
for(i = 0; i < z; i++)
{
fprintf(fout, "%ld ", rez[i]);
}
}
fclose(fout);
return 0;
}
``````