UVa10905 - Children's Game(排序+贪心)

19 篇文章 0 订阅

题目链接

分析:
显然我们要让首位大的数字排在前面

但是有一个问题,如果是这样的数字:
807
80
我们要怎么办呢
显然80807要更优

那么就是短的在前吗,也不一定
809
80
这一组的最优解就是80980
所以我在判断的时候是这么写的:

int pd(int A,int B)
{
    int l1=strlen(a[A]);
    int l2=strlen(a[B]);
    for (int i=0;i<min(l1,l2);i++)
        if (a[A][i]<a[B][i]) return 1;             //A<B
        else if (a[A][i]>a[B][i]) return 0;
    if (l1>l2&&a[A][l2]<a[A][0]) return 1;         //A<B
    if (l2>l1&&a[B][l1]>a[B][0]) return 1;         //A<B
    return 0;
}

写完交上去就是WA啊
于是我只能求助网上前辈的题解
发现他们都是这样排序的:
当前两个字符串a,b,如果a在b前组成的字符串大于b在a前组成的字符串
则a排在b前,否则b在a前

多么简单粗暴的解法

//这里写代码片
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

const int N=1005;
struct node{
    char s[N];
};
node a[N];

int cmp(const node &a,const node &b)
{
    char s1[N],s2[N];
    strcpy(s1,a.s);
    strcat(s1,b.s);
    strcpy(s2,b.s);
    strcat(s2,a.s);
    return strcmp(s1,s2)>0;
}

int main()
{
    int n;
    while (scanf("%d",&n)!=EOF&&n)
    {
        memset(a,0,sizeof(a));
        for (int i=0;i<n;i++) scanf("%s",&a[i].s);

        sort(a,a+n,cmp);

        for (int i=0;i<n;i++) printf("%s",a[i].s);
        printf("\n");
    }
    return 0;
}

如果使用string的话,由于string重载了+,代码更简单

//这里写代码片
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>

using namespace std;

string str[1005];

int cmp(string a,string b)
{
    return a+b>b+a;
}

int main()
{
    int n;
    while (scanf("%d",&n)!=EOF&&n)
    {
        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];
        cout<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值