UVa10905 Children's Game

本文介绍了一道经典的贪心算法题目,通过简单的字符串比较实现排序。利用自定义的比较函数来判断两个字符串拼接后的大小关系,确保最终能够得到最大的数值组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不错的贪心题.

方法也很简单, 排个序就行了.

像这样:

bool cmp(const string &lhs, const string &rhs)
{return lhs + rhs < rhs + lhs;}

为什么呢?

首先, 易证满足排序的基础 : 传递性.

其实, 我们能发现, 这个比价函数排出来的序就是这俩的相对位置, 不会改变 (贪心).

如果 lhs + rhs < rhs + lhs, 那么就是说lhs + rhs组成的数大于rhs + lhs;

于是, 就能确定在最终的答案中, 这俩的位置关系肯定就是这样.

 

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <algorithm>
 5 using namespace std;
 6 const int MAXN = 50 + 2;
 7 
 8 int N;
 9 string s[MAXN], ans;
10 
11 bool cmp(const string &lhs, const string &rhs)
12 {return lhs + rhs < rhs + lhs;}
13 
14 int main()
15 {
16     ios::sync_with_stdio(false);
17     while(cin>>N, N)
18     {
19         for(int i = 1; i <= N; i++) cin>>s[i];
20         sort(s + 1, s + N + 1, cmp);
21         ans.clear();
22         for(int i = 1; i <= N; i++)
23             ans = s[i] + ans;
24         cout<<ans<<endl;
25     }
26     return 0;
27 }

 

转载于:https://www.cnblogs.com/wsmrxc/p/9214346.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值