PAT-乙级 1032 挖掘机技术哪家强(C语言)

代码中的注释部分为调试时所加,删去无影响

#include 
#include

struct studentData{
	int Id;
	int achievement;
};

int main() {
	//获取数据
	int inputNumbers;
	scanf("%d", &inputNumbers);
	struct studentData* pointer;
	pointer = calloc(inputNumbers, sizeof(struct studentData));
	int i;
	for (i = 0; i < inputNumbers; i++){
		scanf("%d", &(pointer+i)->Id);
		scanf("%d", &(pointer + i)->achievement);
	}
	//存放总成绩的数组
	int* intPointer;
	intPointer = calloc(inputNumbers + 1, sizeof(int));
	int input=1;
	//放进去
	while (input<=inputNumbers) {
		i = (pointer + input - 1)->Id;
		*(intPointer + i) += (pointer + input - 1)->achievement;
		input++;
	}
	/*for (i = 1; i <= inputNumbers; i++) {
		printf("%d\n", *(intPointer + i));
	}*/
	//printf("...........................");
	int max = 0,max_id=0;
	for (i = 1; i <= inputNumbers; i++) {
		if (*(intPointer + i) > max) {
			max = *(intPointer + i);
			max_id = i;
		}
	}
	printf("%d %d", max_id,max);
	free(intPointer);
	free(pointer);
	//system("pause");
	return 0;
}

又改了下,尽量少向系统申请一些内存,虽然看起来复杂,其实逻辑上并不难

#include 

struct studentData {
	int id;
	int achievement;
};

int main() {
	int inputNumbers;
	scanf("%d", &inputNumbers);
	struct studentData* dataPointer;
	dataPointer = calloc(inputNumbers, sizeof(struct studentData));
	int i, arrayNumber=0;
	for (i = 0; i < inputNumbers; i++) {
		scanf("%d", &(dataPointer + i)->id);
		scanf("%d", &(dataPointer + i)->achievement);
		if ((dataPointer + i)->id > arrayNumber)
			arrayNumber = (dataPointer+i)->id;
	}
	int* arrayPointer;
	arrayPointer = calloc(arrayNumber + 1, sizeof(int));
	for (i = 0; i < inputNumbers;i++) {
		*(arrayPointer + (dataPointer + i)->id) += (dataPointer + i)->achievement;
	}
	int max = 0, max_id = 0;
	for (i = 1; i <= arrayNumber; i++) {
		if (*(arrayPointer + i) > max) {
			max = *(arrayPointer + i);
			max_id = i;
		}
	}
	printf("%d %d", max_id, max);
	free(dataPointer);
	free(arrayPointer);
	//system("pause");
	return 0;
}

此外,如果使用链表,可以更省一些内存,有兴趣的可以试试

你可能感兴趣的:(PAT-乙级(C语言))