3 aa 10 bb 10 cc 20 cc 20 bb 10 aa 10 3 aa 10 bb 10 cc 20 cc 20 aa 10 bb 10 3 aa 10 bb 10 cc 20 aa 10 bb 10 cc 20
Not Stable cc 20 aa 10 bb 10 Right Error cc 20 aa 10 bb 10
对于不稳定的排序,只是名字变了,分数不会变,所以用两个bool型的变量分别判断是否正确排序和是否稳定排序。
如果名字不正确但分数相同则不稳定排序,如果分数不正确就说明排序错误。
代码如下:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; struct node { char name[55]; int grade; int num; }a[311]; bool cmp(node a,node b) { if (a.grade != b.grade) return a.grade > b.grade; else return a.num < b.num; } int main() { int n; bool flag1; //是否正确排序 bool flag2; //是否稳定排序 while (~scanf ("%d",&n)) { flag1 = flag2 = true; for (int i = 0 ; i < n ; i++) { scanf ("%s %d",a[i].name,&a[i].grade); a[i].num = i; } sort (a,a+n,cmp); for (int i = 0 ; i < n ; i++) { char t1[55]; int t2; scanf ("%s %d",t1,&t2); if (t2 != a[i].grade) flag1 = false; else if (strcmp (t1,a[i].name) != 0) flag2 = false; } if (!flag1) //错误排序 { printf ("Error\n"); for (int i = 0 ; i < n ; i++) printf ("%s %d\n",a[i].name,a[i].grade); } else { if (flag2) printf ("Right\n"); else { printf ("Not Stable\n"); for (int i = 0 ; i < n ; i++) printf ("%s %d\n",a[i].name,a[i].grade); } } } return 0; }