• 二分


                    二分法
    
                D - 又是一道签到题
    

    Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
    Submit Status Practice HDU 2019

    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

    #include<stdio.h>
    int a[10000];
    int a1[10000];
    int main()
    {
        int n,m;
        while(~scanf("%d%d",&n,&m))
        {
            if(n==0&&m==0)
                break;
            for(int i=0; i<n; i++)
            {
                scanf("%d",&a[i]);
            }
            for(int i=0; i<n; i++)
                a1[i]=a[i];
            int x=0,y=n-1,j;
            int flag=1;
            while(x<y)
            {
                j=x+(y-x)/2;
                if(a[j]==m)
                {
                    flag=0;
                    break;
                }
                else if(a[j]>m)
                {
                    y=j;
                }
                else if(a[j]<m)
                    x=j+1;
            }
            if(flag==0)
            {
                for(int i=j+1; i<n+1; i++)
                {
                    a1[i]=a[i-1];
                }
                a1[j]=m;
            }
            else if(a[y]>=m)
            {
                for(int i=x+1; i<n+1; i++)
                {
                    a1[i]=a[i-1];
                }
                a1[x]=m;
            }
            else if(a[y]<m)
            {
                a1[y+1]=m;
            }
            for(int i=0; i<n; i++)
            {
                printf("%d ",a1[i]);
            }
            printf("%d
    ",a1[n]);
        }
    }
  • 相关阅读:
    《算法竞赛入门经典》(刘汝佳)——排序与检索(基础)
    Python中的GIL
    MongoDB 安装
    python3 报错集合
    socket 实例化方法
    socket入门
    Day_6作业_模拟人生
    高阶函数举例
    面向对象_python
    xml
  • 原文地址:https://www.cnblogs.com/da-mei/p/9053378.html
Copyright © 2020-2023  润新知