Jack's Blog

流淌的心,怎能阻拦,吹来的风,又怎能阻挡。

acm--3

Jacob posted @ Sep 16, 2017 11:09:10 PM in 未分类 with tags C语言 acm , 856 阅读

输入一行数字,如果我们把这行数字中的‘5’都看成空格,那么就得到一行用空格分割的若干非负整数(可能有些整数以‘0’开头,这些头部的‘0’应该被忽略掉,除非这个整数就是由若干个‘0’组成的,这时这个整数就是0)。

你的任务是:对这些分割得到的整数,依从小到大的顺序排序输出。        

初玩can,接触第三天的一道水题

第一程序为最初所写,第二个为参考优化后,

#include"stdio.h"
main()
{
    char c;
    while((scanf("%c",&c))!=EOF)
    {
         char a[1300];
         long long int b[1300],sum=0;
         int state=0,temp,k=0,i,j,l;
        for(i=0;c!='\t'&&c!='\n'&&c!=' ';i++)
        {
            a[i]=c;
            scanf("%c",&c);
        }
        a[i]='\0';
        for(j=0;j<i;j++)
        {
            if(a[j]=='5')
            {
                  if(state==1)
                    b[k++]=sum;
                  state=0;
                  sum=0;
            }
            else if(a[j]=='0')
              {
                   state=1;
                sum=sum*10+a[j]-'0';
              }
            else
                {
                   sum=sum*10+a[j]-'0';
                   state=1;
                }
        }
        if(state==1)
            b[k++]=sum;
            k--;
        for(j=0;j<k;j++)
            for(l=0;l<k-j;l++)
        {
            if(b[l]>b[l+1])
            {
                temp=b[l];
                b[l]=b[l+1];
                b[l+1]=temp;
            }
        }
        for(i=0;i<=k-1;i++)
        {
            printf("%lld ",b[i]);
        }
        printf("%lld\n",b[i]);
    }
}

2.

#include"stdio.h"
#include"string.h"
main()
{
 
    int i,len,k,n,temp,j,l;
     char s[5005];
     while(scanf("%s",s)!=EOF)
    {
        int a[5005];
        n=0;
        k=0;
        len=strlen(s);
         s[len]='5';
         i=0;
         while(s[i++]=='5');  //跳过前缀5,防止多输出0
        for(i--;i<=len;++i)
        {
             if(i>0&&s[i]=='5'&&s[i-1]=='5') //忽略连续的5,防止多输出0
                 continue;
            if(s[i]!='5')
                 k=k*10+s[i]-'0';
            else            //遇到5就增加一个数
            {
                 a[n++]=k;
               k=0;
            }
        }
        for(j=0;j<n-1;j++)
            for(l=0;l<n-j-1;l++)
        {
            if(a[l]>a[l+1])
            {
                temp=a[l];
                a[l]=a[l+1];
                a[l+1]=temp;
            }
        }
        for(i=0;i<n-1;i++)
        {
            printf("%d ",a[i]);
        }
        printf("%d\n",a[i]);
    }
}
Avatar_small
Emma 说:
2023年2月01日 20:21

Are you looking for a way to sort and output non-negative integers in ascending order? Look no further! This program provides a simple solution. It takes a line of numbers diamond rings and, by treating the '5' as a space, splits it into non-negative integers which are then sorted and output in ascending order. Written originally on the first day and optimized for reference on the third, this program is an effective solution for your sorting needs!


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter