1055 The World‘s Richest

Posted CSU迦叶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1055 The World‘s Richest相关的知识,希望对你有一定的参考价值。

开始的做法是,对于每一个case,都在整个person数组内进行遍历,把所有年龄符合要求的都放进一个临时数组,然后对临时数组进行排序,再根据要求的数目输出。但是这么做会有一个测试用例因为超时而通不过。

穷则思变。于是改成读入全部数据之后对完整的数组进行排序,之后不再排序。对于每一个case,设置两个变量idx,hasOut,上限分别是全部数据的数量和要求输出的数量,对全部数组进行遍历输出,二者中的任何一个达到上限即停止。注意:idx是每一轮都会自增,hasOut只有在输出一条信息时才自增。

AC代码

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;

const int maxn = 100010;
const double eps = 1e-3;

struct person{
	char name[10] = "";
	int age = 0;
	int worth = 0;
}people[maxn];

bool cmp(person a,person b){
	if(a.worth!=b.worth) return a.worth>b.worth;
	else if(a.age!=b.age)return a.age<b.age;
	else if(strcmp(a.name,b.name)!=0)return strcmp(a.name,b.name)<0;
}

int main(){
	
	int n,k;
	scanf("%d %d",&n,&k);
	
	for(int i=0;i<n;i++){
		scanf("%s",people[i].name);
		scanf("%d",&people[i].age);
		scanf("%d",&people[i].worth);
	}
	sort(people,people+n,cmp);
	
	for(int i=0;i<k;i++){
		printf("Case #%d:\\n",i+1);
		int outputs = 0;
		int Amin = 0;
		int Amax = 0;
		scanf("%d %d %d",&outputs,&Amin,&Amax);

		int hasOut = 0;
		int idx = 0;
		while(idx<n&&hasOut<outputs){
			if(people[idx].age>=Amin&&people[idx].age<=Amax){
				printf("%s %d %d\\n",people[idx].name,people[idx].age,people[idx].worth);
				hasOut ++;
			}
			idx ++;
		}
		
		if(hasOut==0)printf("None");
	}
	
	
}

以上是关于1055 The World‘s Richest的主要内容,如果未能解决你的问题,请参考以下文章