Luogu 1012 - 拼数

题目链接:https://www.luogu.org/problemnew/show/P1012

 

题解:

首先,同等长度的数字,用字典序的方法比较大小,和直接比较数字大小是一样的。

其次,对于任意两个数字进行拼接,哪个放在前面哪个放在后面,直接用字符串拼接起来,比较一下两种情况哪个比较大就可以了。

但是,暂时我还没想到怎么证明,在多个数字拼接时,两两比较拼接大小,再加上排序就可以得出正确答案……

 

AC代码:

#include<bits/stdc++.h>
using namespace std;
int n;
vector<string> v;
bool cmp(const string& a,const string& b) {
    return a+b>b+a;
}
int main()
{
    cin>>n;
    string tp;
    while(n--) cin>>tp, v.push_back(tp);
    sort(v.begin(),v.end(),cmp);
    for(auto s:v) cout<<s;
}

 

今天想了还有另外一种比较方式,不太确定是不是对的,过到是能过:

#include<bits/stdc++.h>
using namespace std;
int n;
vector<string> v;
bool cmp(const string& a,const string& b)
{
    for(int p=0;;p++)
    {
        if(a[p%a.size()]==b[p%b.size()]) continue;
        else return a[p%a.size()]>b[p%b.size()];
    }
}
int main()
{
    cin>>n;
    string tp;
    while(n--) cin>>tp, v.push_back(tp);
    sort(v.begin(),v.end(),cmp);
    for(auto s:v) cout<<s;
}

 

posted @ 2019-03-14 01:40  Dilthey  阅读(131)  评论(0编辑  收藏  举报