PAT1055.The World's Richest (25)

题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1055

PAT上有些题目的时间还是卡的比较紧的,就像这题,题目很平常,但总是有个case过不去。

先给出代码吧,以后再改进。

case 2超时版本:

//#include "StdAfx.h"
#include<stdio.h>
#include<string>
#include<map>
#include<iostream>
#include<vector>
#include<cstring>
#include<stdlib.h>
#include<algorithm>
using namespace std;

struct people{
	char name[10];
	int age;
	int nworth;
};

vector<people>pp;

bool cmp(const struct people &a,const struct people &b){
	
	if(a.nworth!=b.nworth)
		return a.nworth>b.nworth;
	else if(a.age!=b.age)
		return a.age<b.age;
	else 
		return strcmp(a.name,b.name)<0;
}

int main()
{
	//freopen("D://test.txt","r",stdin);
	pp.clear();
	people temp;
	int N,K;
	scanf("%d %d",&N,&K);
	while(N--){
		scanf("%s %d %d",&temp.name,&temp.age,&temp.nworth);
		pp.push_back(temp);
	}
	sort(pp.begin(),pp.end(),cmp);
	int M,Amin,Amax,j;
	for(j=0;j<K;j++){
		scanf("%d %d %d",&M,&Amin,&Amax);
		printf("Case #%d:\n",j+1);
		int count=0;
		bool flag=false;
		vector<people>::size_type i;
		int num=pp.size();
		for(i=0;i<num;++i){
			if(count>=M)
				break;
			if(pp[i].age>=Amin&&pp[i].age<=Amax){
				if(!flag){
					flag=true;
				}
				if(count<M){
					++count;
					printf("%s %d %d\n",pp[i].name,pp[i].age,pp[i].nworth);
				}
			}
		}
		if(!flag)
			printf("None\n");
	}
	
	return 0;
}


case 3超时版本:

//#include "StdAfx.h"
#include<stdio.h>
#include<string>
#include<map>
#include<iostream>
#include<vector>
#include<cstring>
#include<stdlib.h>
#include<algorithm>
using namespace std;

struct people{
	char name[10];
	int age;
	int nworth;
	bool operator<(const people &A)const{
		return age<A.age;
	}
};

vector<people>pp,cc;

bool cmp(const struct people &a,const struct people &b){
	
	if(a.nworth!=b.nworth)
		return a.nworth>b.nworth;
	else if(a.age!=b.age)
		return a.age<b.age;
	else 
		return strcmp(a.name,b.name)<0;
}

int main()
{
	//freopen("D://test.txt","r",stdin);
	pp.clear();
	people temp;
	int N,K;
	scanf("%d %d",&N,&K);
	while(N--){
		scanf("%s %d %d",&temp.name,&temp.age,&temp.nworth);
		pp.push_back(temp);
	}
	//sort(pp.begin(),pp.end(),cmp);
	sort(pp.begin(),pp.end());
	int M,Amin,Amax,j;
	for(j=0;j<K;j++){
		scanf("%d %d %d",&M,&Amin,&Amax);
		printf("Case #%d:\n",j+1);
		int count=0;
		bool flag=false;
		vector<people>::size_type i;
		int num=pp.size();
		cc.clear();

		for(i=0;i<num;++i){
			if(pp[i].age<Amin)continue;
			if(pp[i].age<=Amax)cc.push_back(pp[i]);
			if(pp[i].age>Amax)break;
		}
		if(cc.size()==0){
			printf("None\n");
			break;
		}

		sort(cc.begin(),cc.end(),cmp);


		count=0;
		for(i=0;i<cc.size();++i){
			if(count<M){
				++count;
				printf("%s %d %d\n",cc[i].name,cc[i].age,cc[i].nworth);
			}
		}
	}
	
	return 0;
}



你可能感兴趣的:(编程,ACM,pat,浙大,1055)