首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

浙大PAT_1038:Recover the Smallest Number 答题报告

2013-03-06 
浙大PAT_1038:Recover the Smallest Number 解题报告题目:Given a collection of number segments, you ar

浙大PAT_1038:Recover the Smallest Number 解题报告

题目:Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given {32, 321, 3214, 0229, 87}, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

先贴代码,后解释。

#include<stdio.h>#include<string.h>#include<stdlib.h>int cmp(const void *m,const void *n){  char *a=(char *)m;  char *b=(char *)n;  char tmpa[20],tmpb[20];  strcpy(tmpa,a);  strcpy(tmpb,b);  strcat(tmpa,b);  strcat(tmpb,a);  return strcmp(tmpa,tmpb);}char str[10005][10];int main(){  int i,j,n;  scanf("%d",&n);  for(i=0;i<n;i++){    scanf("%s",str[i]);  }  qsort(str,n,10*sizeof(char),cmp);  int flag=0;  for(i=0;i<n;i++){    for(j=0;str[i][j]!='';j++){      if(flag==0&&str[i][j]=='0');      else {flag=1;printf("%c",str[i][j]);}    }  }  if(flag==0) printf("0");//如果所有段都为零,那么必须输出一个零  printf("n");  return 0;} 
该算法的核心在与compare函数,比较两个数,如3214和87,那么比较一下321487和874214,于是把哪个数放在前面能使得到的数最小便一目了然。

热点排行