1055__部分正确

正确思路应该是先按worth,age,name排好序,然后每一组按min,max去筛选结果


我的思路是:

先按age排序,然后找age 在[min,max]范围内的所有person, 复制到单独一个数组pInRange, 然后对pInRange排序

其中,找min,max用了一个做下标hash的数组并使用binarySearch

结果是2个case错误,1个4分1个3分


#include <stdio.h>
#include <algorithm>
#include <string.h>

int n, k;

typedef struct person{
	char name[10];
	short int age;
	int worth;
};

person p[100000+5];
person * pInRange;

int * age;//年龄,由于给出的query里面min,max不一定正好有对应person的记录,所以不能用int age[200]

int cmpAge(const void * a, const void * b){//只按照age排序
	person pa = *(person *)a;
	person pb = *(person *)b;

	 
	return (pa.age - pb.age);
	 
}

int cmpAll(const void * a, const void * b){
	person pa = *(person *)a;
	person pb = *(person *)b;

	if(pa.worth != pb.worth){
		return (pb.worth - pa.worth);
	}
	/*else if(pa.age != pb.age){
		return (pa.age - pb.age);
	}*/
	return strcmp(pa.name, pb.name);
}

int binaSearch(int l, int r, int val){
	while(l <= r){
		int m = (l+r)/2;
		if(age[m] == val){
			return m;
		}else if(age[m] < val){
			l = m+1;
		}else{
			r = m-1;
		}
	}
	return r;
}


int main(){
	freopen("in.txt","r",stdin);

	scanf("%d%d",&n, &k);

	age = (int *)malloc(n*sizeof(int));
	

	for(int i = 0; i < n; i++){
		person tmp;
		scanf("%s %hd %d", &tmp.name, &tmp.age, &tmp.worth); // short int用%hd
		p[i] = tmp;
	}

	qsort(p, n, sizeof(person),cmpAge);

	
	for(int i = 0; i < n; i++){
		age[i] = p[i].age;	//age数组是升序的,所以可以用二分查找
		//test
		//printf("%s %hd %d\n", p[i].name, p[i].age, p[i].worth);
	}


	
	int m, min, max;

	for(int i = 0; i < k; i++){
		scanf("%d %d %d",&m, &min, &max);

		pInRange = (person *)malloc(sizeof(person)*n);//把在[min,max]范围内的 --所有--person都从p中复制到pInRange
														//此时的前m个person可能worth并不是前m个

		int minPos = binaSearch(0, n-1, min);//age[minPos]==min,或者age[minPos+1]>= min
		while(minPos < n && age[minPos] < min){
			minPos++;
		}
		int maxPos = binaSearch(0, n-1, max); 
		while(maxPos < n && age[maxPos] <= max){// 注意防止数组越界
			maxPos++;
		}//[minPos, maxPos)内的元素就是符合age


		printf("Case #%d:\n",i+1);

		int idx = 0;

		 
		for(int j = minPos; j < maxPos; j++){//
			pInRange[idx++] = p[j];

			if(idx > 100){//只要前M人,而m<=100, 不加这个过滤条件,有个case 会超时
				break;
			}
			//test
			//printf("%s %hd %d\n", p[j].name, p[j].age, p[j].worth);
		}
		//printf("\n");

		if(idx > 0){
			qsort(pInRange, idx, sizeof(person),cmpAll);//再按worth, age, name排序

			for(int j = 0; j < idx && j < m; j++){//可能满足条件的数量idx< m
				printf("%s %hd %d\n", pInRange[j].name, pInRange[j].age, pInRange[j].worth);
			}
		}else{
			printf("None\n");
		}

		free(pInRange);
		pInRange = NULL;

	}

	free(age);
	age = NULL;


	return 0;
}


你可能感兴趣的:(1055__部分正确)