hdu 2019 数列有序!

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2019

数列有序!

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 53086    Accepted Submission(s): 22885


Problem Description
有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。
 

Input
输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0标示输入数据的结束,本行不做处理。
 

Output
对于每个测试实例,输出插入新的元素后的数列。
 

Sample Input
  
  
3 3 1 2 4 0 0
 

Sample Output
  
  
1 2 3 4
 

Author
lcy
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   2024  2095  2090  1096  1047 
 

按照题意,先输入,然后依次比较,移项,最后插入适当位置!

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;


const int MAXN = 110;

int main()
{
    int arr[MAXN], i, n, m;
    while(~scanf("%d %d", &n, &m))
    {
        if(n == 0 && m == 0)
            break;
        for(i = 0; i < n; ++i)
            scanf("%d", &arr[i]);
        for(i = n; i > 0; --i)
        {
            if(arr[i-1] > m)
                arr[i] = arr[i-1];
            else
            {
                arr[i] = m;
                break;
            }
        }
        if(i == 0)
            arr[0] = m;
        for(int i = 0; i < n; ++i)
            printf("%d ", arr[i]);
        printf("%d\n", arr[n]);
    }
    return 0;
}

或者边读入边比较,便输出,但是注意最后的判断,以及输出格式!判断的比较多,注意细节。

int main()
{
    int i, a, n, m;
    bool flag;
    while(~scanf("%d %d", &n, &m))
    {
        if(n == 0 && m == 0)
            break;
            flag = false;
        for(i = 0; i < n-1; ++i)
        {
            scanf("%d", &a);
            if(a >= m && !flag)
            {
                printf("%d ", m);
                flag = true;
            }
            printf("%d ", a);
        }
        scanf("%d", &a);//最后一项输入及输出处理
        if(a >= m && !flag)
            printf("%d %d\n", m, a);
        else if(!flag)
            printf("%d %d\n", a, m);
        else
            printf("%d\n", a);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值