P1012 [NOIP1998 提高组] 拼数

题目

 源代码

一、错误示范

 1 //去比较最高位数字的大小,大的在前面(ASCII比较)
 2 //使用字符串存储多个数字
 3 #include <iostream>
 4 #include <algorithm>
 5 using namespace std;
 6 struct stu
 7 {
 8     string s;
 9 }student[25];
10 bool cmp(stu a,stu b)
11 {
12     return a.s>b.s; //不能直接这么写,有些数据会出错
13     //return a.s+b.s>b.s+a.s;
14 }
15 int main()
16 {
17     int n;
18     cin>>n;
19     for(int i=1;i<=n;i++)
20     {
21         cin>>student[i].s;
22     }
23     sort(student+1,student+1+n,cmp);
24     for(int i=1;i<=n;i++)
25     {
26         cout<<student[i].s;
27     }
28     return 0;
29 }

得分情况:

 二、正确答案

 1 //去比较最高位数字的大小,大的在前面(ASCII比较)
 2 //使用字符串存储多个数字
 3 #include <iostream>
 4 #include <algorithm>
 5 using namespace std;
 6 struct stu
 7 {
 8     string s;
 9 }student[25];
10 bool cmp(stu a,stu b)
11 {
12     //return a.s>b.s; //不能直接这么写,有些数据会出错
13     return a.s+b.s>b.s+a.s;
14 }
15 int main()
16 {
17     int n;
18     cin>>n;
19     for(int i=1;i<=n;i++)
20     {
21         cin>>student[i].s;
22     }
23     sort(student+1,student+1+n,cmp);
24     for(int i=1;i<=n;i++)
25     {
26         cout<<student[i].s;
27     }
28     return 0;
29 }

感悟:两份源代码的区别在十二三行的cmp函数中    错误的是return a.s>b.s             正确的是a.s+b.s>b.s+a.s

错误数据为:

例:当比较"10"和"100"时,错误案例中的cmp的结果是10<100-------因此组装出来的数字为10010(先比较再拼接)

               正确答案中cmp是将组装后的字符串进行比较 也就是将10100和10010比较,得到前者(10100)     (先拼接再比较)

总结:先拼接再比较符合所有数据的情况,而先比较的话,有一部分数据不符合

posted @ 2024-02-19 14:35  连师傅只会helloword  阅读(20)  评论(0编辑  收藏  举报