51Nod1097は、最小数を構成します

問題

これは、整数の最小数を形成するように一列に連結されているnは正の整数を、有しています。

たとえば、次の
接続32321に2のn = 2の最小の整数整数:32132、
312313355:N- = 4、最小の整数整数55,31,312 4、33に結合されます

解決

最適な文字列A + B <B +、ソートすることができます。

NUMセット(x)は、xは数字の文字列であり、NUM(A)10 ^ | B | + NUM(B)<NUM(B) 10 ^ | A | + NUM(A) - > NUM(A)/( 10 ^ | | -1)< NUM(B)/(10 ^ | B | -1)、 ソートすることができます。

CODE1

#include<stdio.h>
#include<math.h>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define io_opt ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
string s[10020];
int n;
int cmp(string x,string y){
    return x+y<y+x;
}
int main(){
    io_opt;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>s[i];
    }
    sort(s+1,s+1+n,cmp);
    string ans="";
    for(int i=1;i<=n;i++){
        ans+=s[i];
    }
    for(int i=0;i<ans.size();i++){
        if(i!=0&&i%1000==0) cout<<endl;
        cout<<ans[i];
    }
    return 0;
}

CODE2

#include<stdio.h>
#include<math.h>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long double ld;
#define io_opt ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
struct E{
    int x,len;
}e[10020];
int n;
int t[20]={1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
int cmp(E x,E y){
    return (ld)x.x/(t[x.len]-1)<(ld)y.x/(t[y.len]-1);
}
int cur=0,tmp[20];
int main(){
    io_opt;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>e[i].x;
        e[i].len=0;
        int xx=e[i].x;
        while(xx){
            e[i].len++;
            xx/=10;
        }
    }
    sort(e+1,e+1+n,cmp);
    int cnt=0;
    for(int i=1;i<=n;i++){
        cur=0;
        while(e[i].x){
            tmp[++cur]=e[i].x%10;
            e[i].x/=10;
        }
        for(int j=cur;j>=1;j--){
            cout<<tmp[j];
            cnt++;
            if(cnt%1000==0){
                cout<<endl;
            }
        }
    }
    return 0;
}

おすすめ

転載: www.cnblogs.com/sz-wcc/p/11704810.html