題意:
給定n個正整數,你的任務就是把他們連接成一個最大的整數
分析:
排序後直接輸出是不行的,反例:13, 1312
如果兩個數字的位數相等,那麼可以直接判斷,如果不等的話,對於某個數字要麼在前,要麼在後,枚舉這兩種情況就可以了
Code:
#include <set>
#include <map>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <cstdio>
#include <bitset>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
#define DIR 4
#define DIM 2
#define STATUS 2
#define MAXN 1000 + 10
#define MAXM 1000000 + 10
#define oo (~0u)>>1
#define INF 0x3F3F3F3F
#define REPI(i, s, e) for(int i = s; i <= e; i ++)
#define REPD(i, e, s) for(int i = e; i >= s; i --)
static const double EPS = 1e-5;
int hash[MAXN];
char rst[MAXM];
char str[MAXN][MAXN];
int select_max(int n)
{
int idx = 0;
REPI(i, 1, n) {
if( hash[i] ) {
continue;
}
if( strlen(str[idx]) == strlen(str[i]) ) {
if( strcmp(str[i], str[idx]) > 0 ) {
idx = i;
}
}
else {
char tmpa[MAXN];
char tmpb[MAXN];
strcpy(tmpa, str[idx]);
strcpy(tmpb, str[i]);
strcat(tmpa, str[i]);
strcat(tmpb, str[idx]);
if( strcmp(tmpa, tmpb) < 0 ) {
idx = i;
}
}
}
hash[idx] = 1;
return idx;
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int n;
str[0][0] = '0', str[0][1] = '\0';
while( scanf("%d", &n) ) {
if( !n ) {
break;
}
REPI(i, 1, n) {
scanf("%s", str[i]);
}
int idx = 0;
memset(hash, 0, sizeof(hash));
REPI(i, 1, n) {
int tar = select_max(n);
REPI(j, 0, strlen(str[tar])-1) {
rst[idx ++] = str[tar][j];
}
}
rst[idx] = '\0';
printf("%s\n", rst);
}
return 0;
}