Bootstrap

数据结构实验作业题

题目:

解题代码(不能用来提交,但是是另一个思路):

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
//线性结构及扩展
//第62题
typedef struct Line
{
	int* arr;
	int num;
}Line;
int compare(int k, int linenum, Line** l)
{
	Line* line = *l;
	//printf("%d ", k);
	int* arr1;
	int* arr2;
	arr1 = (int*)malloc(linenum * sizeof(int));
	arr2 = (int*)malloc(linenum * sizeof(int));
	int i = 0;
	int j = 0;
	for (;i < linenum; i++)
	{
		arr1[i] = line[i].arr[line[i].num - 1];
		if (arr1[i] > k)
		{
			arr2[j] = i;
			j++;
		}
	}
	if (j == 0)
	{
		free(arr1);
		free(arr2);
		return linenum;
	}
	int min = arr2[0];
	for (i = 0; i < j; i++)
	{
		if (arr1[arr2[i]] < arr1[min])
			min = arr2[i];
	}
	//printf("%d\n", min);
	free(arr1);
	free(arr2);
	return min;
}
int main()
{
	int N = 0;
	Line* line;
	int* s;
	scanf("%d", &N);
	getchar();
	line = (Line*)malloc(N * sizeof(Line));
	s = (int*)malloc(N * sizeof(int));
	int i = 0;
	for (; i < N; i++)
	{
		line[i].arr = (int*)malloc(N * sizeof(int));
		line[i].num = 0;
		scanf("%d", &s[i]);
		getchar();
	}
	int linenum = 0;
	for (i = 0; i < N; i++)
	{
		if (i == 0)
		{
			line[0].arr = (int*)malloc(sizeof(int));
			line[0].arr[0] = s[0];
			line[0].num++;
			linenum++;
		}
		else
		{
			int m = compare(s[i], linenum, &line);
			if (m == linenum)
			{
				line[m].arr = (int*)malloc(sizeof(int));
				line[m].arr[0] = s[i];
				line[m].num++;
				linenum++;
			}
			else
			{
				line[m].arr = (int*)realloc(line[m].arr, (line[m].num + 1) * sizeof(int));
				line[m].arr[line[m].num] = s[i];
				line[m].num++;
			}
		}
	}
	printf("%d", linenum);
	return 0;
}

大致思路就是让列车挨个进轨道,每进一个就和比较每条轨道上末尾列车的序号,使得进去的序号要小于当前轨道内末尾的序号,且要保证该进去的序号不仅小于当前轨道末尾列车的序号,还要小于其他轨道末尾列车的序号,如果都不满足,那就再开一条新的轨道进去,以此类推,最后的linenum即为所求,但是内存超限,所以提交出现报错,仅记录一个思路,欢迎指正错误!

;