UVA 10905 Children's Game

来源:互联网 发布:贾利尔.奥卡福数据 编辑:程序博客网 时间:2024/05/29 13:59

刚开始做这题,没想到用sort排序,也没想到用string来存储输入的数字,弄的特别麻烦。现在看来,只要弄懂sort自定义排序方法,就很好做了。

sort所在头文件:
#include <algorithm>

首先,sort默认的是升序排序

好在,可以自己写一个cmp函数,使sort按指定意图进行排序

譬如:

bool cmp(int a,int b){    return a>b;}sort(a,a+100,cmp);

int cmp( const int &a, const int &b ){    if( a > b )       return 1;    else       return 0;}sort(a,a+n,cmp);

都是对数组a降序排序

又如:

int cmp( const POINT &a, const POINT &b ){    if( a.x < b.x )       return 1;    else       if( a.x == b.x ){          if( a.y < b.y )             return 1;          else             return 0;        }       else          return 0;}sort(a,a+n,cmp);

是先按x升序排序,若x值相等则按y升序排

刚开始看不懂意思,多看几个就找出规律了。

下面是源代码

#include<iostream>#include<string.h>#include<algorithm>using namespace std;int n;string str[55];int cmp(string a,string b){    return a+b>b+a;}void solve(){    for(int i=0; i<n; i++)        cin>>str[i];    sort(str,str+n,cmp);    for(int i = 0; i < n; i++) cout<<str[i];}int main(){    while(cin>>n&&n)    {        solve();        cout<<endl;    }    return 0;}


 

0 0
原创粉丝点击