一开始用二维数组保存,但是内存占用太大,复杂度太高,过不了所有点
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef struct node
{
int age;
char name[9];
int worth;
}record;
bool cmp(record a,record 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()
{
record s[10000];
record temp1[10][100];
int n,k,q[100000];
scanf("%d %d",&n,&k);
for(int i =0;i<n;i++)
{
scanf("%s %d %d",s[i].name,&s[i].age,&s[i].worth);
// printf("%s %d %d\n",s[i].name,s[i].age,s[i].worth);
}
int out[100],l,r,flag[1000] = {0},temp[1000] = {0};
for(int j = 1;j<=k;j++)
{
int sum = 0;
scanf("%d %d %d",&out[j],&l,&r);
for(int i =0;i<n;i++)
{
if(s[i].age <=r && s[i].age >= l)
{
flag[j] = 1;
temp1[j][sum].age = s[i].age;
temp1[j][sum].worth = s[i].worth;
strcpy(temp1[j][sum].name,s[i].name);
sum++;
}
}
temp[j] = sum ;
sort(temp1[j],temp1[j]+sum,cmp);
}
for(int i = 1;i<=k;i++)
{
printf("Case #%d:\n",i);
if(flag[i] == 1)
{
for(int j = 0;j<out[i] && j<temp[i];j++ )
{
printf("%s %d %d\n",temp1[i][j].name,temp1[i][j].age,temp1[i][j].worth);
}
}
else
printf("None\n");
}
return 0;
}
在这里插入代码片
emmmm
看了算法笔记,好像根本没有必要来设置二维数组
直接排序,根据年龄要求从前往后输出。
设置一个P来记录有多少符合的,为0就输出none
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef struct node
{
int age;
char name[9];
int worth;
}record;
bool cmp(record a,record 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()
{
record s[100010],sum[100010];
int age[100010] = {0};
int n,k;
scanf("%d %d",&n,&k);
for(int i =0;i<n;i++)
{
scanf("%s %d %d",s[i].name,&s[i].age,&s[i].worth);
// printf("%s %d %d\n",s[i].name,s[i].age,s[i].worth);
}
sort(s,s+n,cmp);
int index = 0;
for(int i =0;i<n;i++)
{
if(age[s[i].age] < 100)
{
age[s[i].age]++;
sum[index] = s[i];
index ++;
}
}
int m,l,r;
for(int i = 1;i<=k;i++)
{
scanf("%d %d %d",&m,&l,&r);
printf("Case #%d:\n",i);
int P=0;
for(int j = 0;j<index && P<m;j++ )
{
if(sum[j].age <=r && sum[j].age >=l)
{
printf("%s %d %d\n",sum[j].name,sum[j].age,sum[j].worth);
P++;
}
}
if(P==0)
printf("None\n");
}
return 0;
}
在这里插入代码片