HDU 1106 排序

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1106

题目难点在分割整数吧,快排可以套用模板。

方法1  快排

View Code
 1 #include<stdio.h>
 2 char str[1010];
 3 int a[100000];
 4 void qsort(int a[],int l,int r)
 5 {
 6     int x=a[l],i=l,j=r;
 7     if(l>=r) return;
 8     while(i<j)
 9     {
10         while(i<j&&a[j]>=x)j--;
11         a[i]=a[j];
12         while(i<j&&a[i]<=x)i++;
13         a[j]=a[i];
14     }
15     a[i]=x;
16     qsort(a,l,i-1);
17     qsort(a,i+1,r);
18 }
19 int main()
20 {
21     int k,i,sum;
22     while(~scanf("%s",str))
23     {
24         k=0;i=0;
25         while(str[i]!='\0')
26         {
27             sum=0;
28             if(str[i]=='5')
29             {
30                 i++;
31                 continue;
32             }
33             while(str[i]!='5'&&str[i]!='\0')
34             {
35                 sum=sum*10+str[i]-'0';
36                 i++;
37             }
38             a[k]=sum;
39             k++;
40         }
41         qsort(a,0,k-1);
42         for(i=0;i<k-1;i++)
43         {
44             printf("%d ",a[i]);
45         }
46         printf("%d\n",a[i]);
47     }
48     return 0;
49 }

在网上学了一招。。。strtok函数,感觉这个比较新鲜。下面从百度百科摘抄。。
功能 
  分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。 
说明 
  strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。 
返回值 
  从s开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。 
  所有delim中包含的字符都会被滤掉,并将被滤掉的地方设为一处分割的节点。

方法2

View Code
 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 int cmp(const void*a,const void*b)
 5 {
 6     return *(int*)a-*(int*)b;
 7 }
 8 int main()
 9 {
10     int n,i,cnt;
11     int b[1100];
12     char a[1100],*p;
13     while(~scanf("%s",a))
14     {
15         cnt=0;
16         p=strtok(a,"5");
17         while(p!=NULL)
18         {
19             b[cnt++]=atoi(p);
20             p=strtok(NULL,"5");
21         }
22         qsort(b,cnt,sizeof(b[0]),cmp);
23         printf("%d",b[0]);
24         for(i=1;i<cnt;i++)
25             printf(" %d",b[i]);
26         putchar('\n');
27     }
28     return 0;
29 }

 

原文地址:https://www.cnblogs.com/timeship/p/2622133.html