Cod sursa(job #251292)

Utilizator willliIonel Bratianu willli Data 2 februarie 2009 11:35:50
Problema Subsir crescator maximal Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 2.34 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 +1) * sizeof(long));
	P = (long *)malloc(n * sizeof(long));
	B = (long *)malloc(n * sizeof(long));
	//process the matrix
	max = 1;
	pmax = 1;
	m = 0;
	for (i = 0; i < n; i++)
	{
		//binary search.
		j = 1;
		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("m = %ld l = %ld j = %ld a[%ld]  %ld\n", m, l, j,i, a[i]);
		while (j <= l)
		{
			m = (j + l) / 2;
			//printf("m = %ld l = %ld j = %ld M[%ld] = %ld a[%ld] %ld\n", m, l, j, m, M[m], M[m], a[M[m]]);
			if (a[i] <= a[M[m]])
				l = m - 1;
			else
				j = m + 1;
		}
		//printf("m = %ld l = %ld j = %ld\n", m, l, j);
		//check if 
		M[j] = i;
		if (j <= 0)
			P[i] = -1;
		else
			P[i] = M[j - 1];/*
		printf("M[%ld] = %ld\n", j, M[j]);
		printf("P[%ld] = %ld\n", i, P[i]);*/
		if (j > max)
		{
			max++;
			pmax = i;
		}
		/*
		if (j+1 == 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 pmax = %ld\n", max, i);
	}
	*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] = a[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);
	}
	//read dimension of vectors
	fscanf(fin, "%ld", &n);

	//read the vectors
	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;
}