天天看點

1754:字元串數組排序問題(4.1算法之排序和算法性能)1754:字元串數組排序問題

1754:字元串數組排序問題

總時間限制: 1000ms 記憶體限制: 65536kB

描述

給定一組字元串,按指定的排序方式輸出這些字元串。排序可是自然順序(inc)、自然逆序(dec)、忽略大小寫順序(ncinc)、忽略大小寫逆序(ncdec)等。

輸入

輸入有多行,第一行為一個表明排序方式的字元串見題面,第二行為字元串的數目。

其餘各行每行一個字元串,字元串中間可能空格,前後也可能有空格,但前後的空格要忽略。

輸出

輸出也有多行,按指定的順序輸出輸入的字元串。

樣例輸入

ncdec

3

Hello World!

You’re right!

haha! you’re wrong!

樣例輸出

You’re right!

Hello World!

haha! you’re wrong!

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
//http://noi.openjudge.cn/ch0401/1754/
//講真,感覺寫的很垃圾,沒想到char的二維數組在sort裡面沒法直接用
//是以又改成了struct類型的,cmp寫了兩個方法,一個大小寫敏感,一個忽略大小寫
//輸入的擷取也是費了不少勁,反正寫的不好 
struct str{
    char s[];
};
int n;
char a[],b,x[][],tmp;
str y[];
bool cmp(str c,str d){
    int len=min(strlen(c.s),strlen(d.s));
    for(int i=;i<len;i++){
        if(c.s[i]!=d.s[i]){
            return c.s[i]<d.s[i];
        }
    }
    return strlen(c.s)<strlen(d.s);

}
bool cmp2(str c,str d){
    int len=min(strlen(c.s),strlen(d.s));
    for(int i=;i<len;i++){
        if(tolower(c.s[i])!=tolower(d.s[i])){
            return tolower(c.s[i])<tolower(d.s[i]);
        }
    }
    return strlen(c.s)<strlen(d.s);
}
int main(){
    cin>>a>>n>>b;
    cin.putback(b);
    for(int i=;i<n;i++){
        cin.getline(x[i],);
        int l=,r=strlen(x[i])-,k=;
        while(x[i][l]==' '){
            l++;
        }
        while(x[i][r]==' '){
            r--;
        }
        for(int j=l;j<=r;j++){
            y[i].s[k++]=x[i][j];
        }
        y[i].s[k]='\0';
    }

    switch(a[]){
        case 'i':
            sort(y,y+n,cmp);
            for(int i=;i<n;i++)
                cout<<y[i].s<<endl;
            break;
        case 'd':
            sort(y,y+n,cmp);
            for(int i=n-;i>=;i--)
                cout<<y[i].s<<endl;
            break;
        case 'n':
            sort(y,y+n,cmp2);
            if(a[]=='i'){
                for(int i=;i<n;i++)
                    cout<<y[i].s<<endl;
            }
            else{
                for(int i=n-;i>=;i--)
                    cout<<y[i].s<<endl;
            }
            break;
    }

} 
           

别人寫的,用的string數組,簡單了一逼,原來string數組可以用sort,欲哭無淚!

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
string p;int n;
inline char bian(char c){
if(c<='Z'&&c>='A')
return c+'a'-'A';
else return c;
}
bool cmp(string a,string b){
for(int i=;i<;i++){
if(bian(a[i])<bian(b[i]))return true;
if(bian(a[i])>bian(b[i]))return false;
}
}
string a[];
int main(){
cin>>p>>n;
for(int i=;i<=n;i++)
getline(cin,a[i]);
if(p=="inc"){
sort(a+,a+n+);
for(int i=;i<=n;i++)
cout<<a[i]<<endl;
//system("pause");
return ;
}
if(p=="dec"){
sort(a+,a+n+);
for(int i=n;i>=;i--)
cout<<a[i]<<endl;
//system("pause");
return ;
}
sort(a+,a+n+,cmp);
if(p=="ncinc"){
for(int i=;i<=n;i++)
cout<<a[i]<<endl;
//system("pause");
return ;
}
for(int i=n;i>=;i--)
cout<<a[i]<<endl;
//system("pause");
return ;
}
           

繼續閱讀