自己写的时候发现一个问题,printf不可以用来输出vector中的结构体元素!!!
其他也没啥了,但是还有一个case超时。
超时是因为进行了多次sort,这样如果查询的range很多的话,就会浪费很多时间,不足以弥补使用多个向量存储节省的查询年龄的时间。
推荐一版:https://blog.csdn.net/xtzmm1215/article/details/39019739
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
struct person{
int worth;
int age;
string name;
};
bool cmp(person p1,person p2){
if(p1.worth==p2.worth){
if(p1.age==p2.age){
return p1.name<p2.name;
}
else
return p1.age<p2.age;
}
else
return p1.worth>p2.worth;
}
vector<person> P[200];
vector<person> res;
int main(){
int N,K,i;
scanf("%d%d",&N,&K);
char name[9];
int age,worth;
for(i=0;i<N;i++){//不能直接scanf string,至少要string.resize(9),但是这样又固定大小了。。。
scanf("%s %d %d",&name,&age,&worth);
person p;
p.name=name;
p.age=age;
p.worth=worth;
P[age].push_back(p);
}
int amont,s,e,k,t,j;
for(i=0;i<K;i++){
res.clear();
scanf("%d %d %d",&amont,&s,&e);
for(j=s;j<=e;j++){
for(k=0;k<P[j].size();k++)
res.push_back(P[j][k]);
}
sort(res.begin(),res.end(),cmp);
printf("Case #%d:\n",i+1);
for(t=0;t<amont&&t<res.size();t++){
//printf("%s %d %d\n",res[t].name,res[t].age,res[t].worth);//***printf不可用于输出vector的元素!!!!
cout<<res[t].name<<" "<<res[t].age<<" "<<res[t].worth<<endl;
}
if(res.size()==0)
cout<<"None"<<endl;
}
system("pause");
return 0;
}