大家都知道,快速排序是不稳定的排序方法。
如果对于数组中出现的任意a[i],aj,其中a[i]==a[j],在进行排序以后a[i]一定出现在a[j]之前,则认为该排序是稳定的。
某高校招生办得到一份成绩列表,上面记录了考生名字和考生成绩。并且对其使用了某排序算法按成绩进行递减排序。现在请你判断一下该排序算法是否正确,如果正确的话,则判断该排序算法是否为稳定的。
Input
本题目包含多组输入,请处理到文件结束。
对于每组数据,第一行有一个正整数N(0<N<300),代表成绩列表中的考生数目。
接下来有N行,每一行有一个字符串代表考生名字(长度不超过50,仅包含’a’~‘z’),和一个整数代表考生分数(小于500)。其中名字和成绩用一个空格隔开。
再接下来又有N行,是上述列表经过某排序算法以后生成的一个序列。格式同上。
Output
对于每组数据,如果算法是正确并且稳定的,就在一行里面输出"Right"。如果算法是正确的但不是稳定的,就在一行里面输出"Not Stable",并且在下面输出正确稳定排序的列表,格式同输入。如果该算法是错误的,就在一行里面输出"Error",并且在下面输出正确稳定排序的列表,格式同输入。
注意,本题目不考虑该排序算法是错误的,但结果是正确的这样的意外情况。
Sample Input
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
Sample Output
Not Stable
cc 20
aa 10
bb 10
Right
Error
cc 20
aa 10
bb 10
错误代码:
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct student{
int number;
string name;
int score;
};
typedef struct student1{
string name;
int score;
};
bool cmp1(student a,student b){
return a.name <b.name ;
}
bool cmp2(student a,student b){
return a.score >b.score ;
}
bool cmp3(student a,student b){
return a.number <b.number ;
}
student stu[310];
student1 stu1[310];
int main(){
int t;
while(cin>>t){
for(int i=0;i<t;i++){
stu[i].number =i;
cin>>stu[i].name >>stu[i].score;
}
sort(stu,stu+t,cmp3);
sort(stu,stu+t,cmp1);
sort(stu,stu+t,cmp2);
for(int i=0;i<t;i++){
cin>>stu1[i].name >>stu1[i].score;
}
int flag1=0,flag2=0;
for(int i=0;i<t;i++){
if(stu[i].score !=stu1[i].score){
flag1=1;
break;
}
}
for(int i=0;i<t;i++){
if(stu[i].name !=stu1[i].name ){
flag2=1;
break;
}
}
if(flag1==0){
if(flag2==0){
cout<<"Right"<<endl;
}
else{cout<<"Not Stable"<<endl;
for(int i=0;i<t;i++){
cout<<stu[i].name <<" "<<stu[i].score<<endl;
}
}
}
else{
cout<<"Error"<<endl;
for(int i=0;i<t;i++){
cout<<stu[i].name <<" "<<stu[i].score<<endl;
}
}
}
return 0;
}`
因为之前一直认为只要name和score一样,输出的就是对的,总是忽略sort在排序时总是会出现乱序的情况。
经大佬提醒,在每组输入加了id,即下列的number
ac代码
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct student{
int number;
string name;
int score;
};
typedef struct student1{
string name;
int score;
};
bool cmp1(student a,student b){
if(a.name ==b.name) return a.number <b.number ;
return a.name <b.name ;
}
bool cmp2(student a,student b){
if(a.score ==b.score ) return a.number <b.number ;
return a.score >b.score ;
}
student stu[310];
student1 stu1[310];
int main(){
int t;
while(cin>>t){
for(int i=0;i<t;i++){
stu[i].number =i;
cin>>stu[i].name >>stu[i].score;
}
sort(stu,stu+t,cmp1);
sort(stu,stu+t,cmp2);
for(int i=0;i<t;i++){
cin>>stu1[i].name >>stu1[i].score;
}
int flag1=0,flag2=0;
for(int i=0;i<t;i++){
if(stu[i].score !=stu1[i].score){
flag1=1;
break;
}
}
for(int i=0;i<t;i++){
if(stu[i].name !=stu1[i].name ){
flag2=1;
break;
}
}
if(flag1==0){
if(flag2==0){
cout<<"Right"<<endl;
}
else{cout<<"Not Stable"<<endl;
for(int i=0;i<t;i++){
cout<<stu[i].name <<" "<<stu[i].score<<endl;
}
}
}
else{
cout<<"Error"<<endl;
for(int i=0;i<t;i++){
cout<<stu[i].name <<" "<<stu[i].score<<endl;
}
}
}
return 0;
}