一、排序_练习_1023_2

来源:互联网 发布:淘宝直通车行业点击率 编辑:程序博客网 时间:2024/06/05 20:38

拿到这道题依然分析时间限制条件和空间限制条件。跟上文一样,也是采用sort来进行排序。而算法的思路读懂了题目后是很清楚的,因此这次主要说明在实现上的各种错误。首先,我写出的代码是用switch控制n的输入类型的,用三个自定义比较规则函数cmp1cmp2cmp3来作为sort的最后一个参数传递进去。

 

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<algorithm>using namespace std;struct information{    char code[7];    char name[9];    int score;}buf[10001];bool cmp1(information a,information b){          return strcmp(a.code,b.code)<0;}bool cmp2(information a,information b){      int tmp=strcmp(a.name,b.name);  if(tmp!=0)  return tmp<0;  else if(tmp==0) return strcmp(a.code,b.code)<0;}bool cmp3(information a,information b){if(a.score!=b.score)return a.score<b.score;else if(a.score==b.score)return strcmp(a.code,b.code)<0;}int main(){int n,i,c,j=0;while(scanf("%d %d",&n,&c)!=EOF){j++;for(i=0;i<n;i++){scanf("%s%s%d",buf[i].code,buf[i].name,&buf[i].score);}switch(c){case 1:sort(buf,buf+n,cmp1);case 2:sort(buf,buf+n,cmp2);case 3:sort(buf,buf+n,cmp3);case 0:exit(1);}printf("Case %d:\n",j);for(i=0;i<n;i++){printf("%s %s %d\n",buf[i].code,buf[i].name,buf[i].score);}}return 0;}

为什么会出现问题?原因一:数组开的不够大。实际上,buf需要开到100000这么大,这样才能承受OJ的极限数据测试。原因二:用多个if代替switch。这个具体原因我还没想很清楚,但我估计是由于OJ自身的问题所致。更改这两个方面的问题后,很快便AC了。

 

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<algorithm>using namespace std;struct information{    char code[7];    char name[9];    int score;}buf[100001];bool cmp1(information a,information b){          return strcmp(a.code,b.code)<0;}bool cmp2(information a,information b){      int tmp=strcmp(a.name,b.name);  if(tmp!=0)  return tmp<0;   return strcmp(a.code,b.code)<0;}bool cmp3(information a,information b){if(a.score!=b.score)return a.score<b.score;return strcmp(a.code,b.code)<0;}int main(){int n,i,c,j=0;while(scanf("%d %d",&n,&c)!=EOF){j++;for(i=0;i<n;i++){scanf("%s%s%d",buf[i].code,buf[i].name,&buf[i].score);}if(c==1)sort(buf,buf+n,cmp1);if(c==2)sort(buf,buf+n,cmp2);if(c==3)sort(buf,buf+n,cmp3);if(c==0)exit(1);printf("Case %d:\n",j);for(i=0;i<n;i++){printf("%s %s %d\n",buf[i].code,buf[i].name,buf[i].score);}}return 0;}

0 0