pat 1038 Recover the Smallest Number

本文介绍了一种特殊的字符串排序问题,通过自定义比较函数而非简单的字典序来实现字符串数组的最优排序,以形成最小数值。文章提供了完整的AC代码,并讨论了避免前导零的方法。

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

此题不能简单对其进行排序,因为32不一定排321前面,后来发现规律:对于最小的序列中的任意两个数 a,b 如果 a在b前面 当且仅当 a在b前面 < b在a前面。 原本是将所有串合并一串,再检测前导0,这样最后一点会超时。干脆直接检测。

AC代码:

//1038 19:12 -19:43
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
char str[10005][10];
 
// bool cmp(const char[10] &a, const char[10] &b)
// {
// 
//     return strcmp(a,b)<0;
// }
char res[100005];
int cmp(const void *a,const void *b)
{
    char *x=(char *)a;
    char *y=(char *)b;
	char tmpa[20],tmpb[20];
	strcpy(tmpa,x);
	strcpy(tmpb,y);
	strcat(tmpa,y);//tmpa=xy
	strcat(tmpb,x);//tmpb=yx
    return strcmp(tmpa,tmpb)>0;//当tmpa<tmpb时,a在b前;当tmpa>tmpb时,b在a前
}
int main()
{
    int i,n;
    freopen("C:\\Documents and Settings\\Administrator\\桌面\\input.txt","r",stdin);
 
    scanf("%d",&n);
    for(i=0;i<n;i++){
        getchar();
        scanf("%s",str[i]);
    }
 
 
 
    qsort(str,n,sizeof(str[0]),cmp);
	
// 	strcpy(res,str[0]);//把所有串合并成一串,也可以,但会超时
// 	for(i=1;i<n;i++){
// 		strcat(res,str[i]);
// 	}
// 	int fg=0;
// 	for(i=0;i<strlen(res);i++){
// 		if(fg==0&&res[i]!='0'){
// 			fg=1;
// 
// 		}
// 		if(fg==1)
// 			printf("%c",res[i]);
// 
// 	}
// 	if(fg==0)
// 		printf("0");
	int j,fg=0;
	for(i=0;i<n;i++){
		for(j=0;str[i][j]!='\0';j++){
			if(fg==0&&str[i][j]=='0');
			else{
				fg=1;
				printf("%c",str[i][j]);
			} 
		}

	}
	if(fg==0)
		printf("0");

	
    return 0;
	
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值