测试点一超时是因为你用了cin,cout,搞得程序很慢,所以以后写pat的题目别用cin,cout,用的时候很爽,改的时候就知道错了,还有不要用scanf输入string,string是c++的,要用cin,所以这题如果名字在结构体用了string定义就要改成char name[10]了,bool cmp的时候就不能用return a.name<b.name了,这样的话就是只比较首字母,要用cstring库里面的strcmp判断大小,sort里面的cmp是当bool返回为真的时候交换指针,所以要写成return strcmp(a.name,b,name)<0;
测试点二超时的话,我估计你的方法就是先用一个数组全部存起来,然后在做一个临时数组vector,把符合条件的数据都存在vector里面,然后用完再v.cear,但是,你看看你的sort再在哪里,是不是sort了很多次,所以测试点2才会超时,别问问就是我原来就是这么干的,改成只sort一次,再整一个计数器,要输出多少个就输出多少个就好了;
代码:
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cstring>
using namespace std;
struct node{
int age;
char name[10];
int worth;
};
bool cmp(node a,node b){
if(a.worth==b.worth&&a.age==b.age){
return strcmp(a.name,b.name)<0;
}else if(a.worth==b.worth){
return a.age<b.age;
}else {
return a.worth>b.worth;
}
}
int main(){
int n,m,column,age1,age2,flag=0,cnt=0;
cin>>n>>m;
vector<node> v(n);
for(int i=0;i<n;i++){
scanf("%s %d %d",v[i].name,&v[i].age,&v[i].worth);
}
sort(v.begin(),v.end(),cmp);
for(int i=1;i<=m;i++){
scanf("%d %d %d",&column,&age1,&age2);
printf("Case #%d:\n",i);
for(int j=0;j<n;j++){
if(v[j].age>=age1&&v[j].age<=age2&&cnt!=column){
cout<<v[j].name<<" "<<v[j].age<<" "<<v[j].worth<<"\n";
cnt++;
flag=1;
}
}
if(flag==0){
printf("None\n");
}
flag=0;cnt=0;
}
return 0;
}