1754:字符串数组排序问题(4.1算法之排序和算法性能)

来源:互联网 发布:淘宝虚拟现实vr购物 编辑:程序博客网 时间:2024/06/05 03:27

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[10000];};int n;char a[10],b,x[10000][10000],tmp;str y[10000];bool cmp(str c,str d){    int len=min(strlen(c.s),strlen(d.s));    for(int i=0;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=0;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=0;i<n;i++){        cin.getline(x[i],100000);        int l=0,r=strlen(x[i])-1,k=0;        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[0]){        case 'i':            sort(y,y+n,cmp);            for(int i=0;i<n;i++)                cout<<y[i].s<<endl;            break;        case 'd':            sort(y,y+n,cmp);            for(int i=n-1;i>=0;i--)                cout<<y[i].s<<endl;            break;        case 'n':            sort(y,y+n,cmp2);            if(a[2]=='i'){                for(int i=0;i<n;i++)                    cout<<y[i].s<<endl;            }            else{                for(int i=n-1;i>=0;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=0;i<300;i++){if(bian(a[i])<bian(b[i]))return true;if(bian(a[i])>bian(b[i]))return false;}}string a[50];int main(){cin>>p>>n;for(int i=0;i<=n;i++)getline(cin,a[i]);if(p=="inc"){sort(a+1,a+n+1);for(int i=1;i<=n;i++)cout<<a[i]<<endl;//system("pause");return 0;}if(p=="dec"){sort(a+1,a+n+1);for(int i=n;i>=1;i--)cout<<a[i]<<endl;//system("pause");return 0;}sort(a+1,a+n+1,cmp);if(p=="ncinc"){for(int i=1;i<=n;i++)cout<<a[i]<<endl;//system("pause");return 0;}for(int i=n;i>=1;i--)cout<<a[i]<<endl;//system("pause");return 0;}
阅读全文
0 0
原创粉丝点击