• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
dwtfukgv
博客园    首页    新随笔    联系   管理    订阅  订阅
UVa 10905 Children's Game (贪心。。。)

题意:给定n个正整数,把它们连接成一个最大的整数。

析:本来以为是按字典序排一下就好,可是一看第二个样例,发现并不是这样的,这种比较不能简单以字典序比较,

而是应该用一种“环”的思想去比较。也就是A串和B串都已这种环的方式去计较,知道第一个不相同的字符出现则跳出。

我们要先算好它们的最小公倍数,不然万一是两个一样的串,就造成死循环了,这样的并不难写。但是我一看网上的题解,

就傻眼了,大神就是大神,代码是如此精辟,如果简洁。。。我的代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;
const int maxn = 5000 + 10;

vector<string> v;
int gcd(int a, int b){  return 0 == b ? a : gcd(b, a%b); }

int lcm(int a, int b){  return a*b / gcd(a, b); }

bool cmp(const string &s1, const string &s2){
    int l1 = s1.size(), l2 = s2.size();
    int n = lcm(l1, l2);

    for(int i = 0; i < n; ++i)
        if(s1[i%l1] != s2[i%l2])  return s1[i%l1] > s2[i%l2];
    
    return false;
}

int main(){
    int n;
    while(~scanf("%d", &n) && n){
        v.clear();
        for(int i = 0; i < n; ++i){
            string s;  cin >> s;
            v.push_back(s);
        }
        sort(v.begin(), v.end(), cmp);
        for(int i = 0; i < n; ++i)
            cout << v[i];
        printf("\n");
    }
    return 0;
}

 

大神的代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;
const int maxn = 5000 + 10;

vector<string> v;

bool cmp(const string &s1, const string &s2){  return s1 + s2 > s2 + s1; }

int main(){
    int n;
    while(~scanf("%d", &n) && n){
        v.clear();
        for(int i = 0; i < n; ++i){
            string s;  cin >> s;
            v.push_back(s);
        }
        sort(v.begin(), v.end(), cmp);
        for(int i = 0; i < n; ++i)
            cout << v[i];
        printf("\n");
    }
    return 0;
}

 

posted on 2016-05-29 20:12  dwtfukgv  阅读(218)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3