[hdu 2019] 数列有序

来源:互联网 发布:windows powershell 编辑:程序博客网 时间:2024/04/29 16:36

数列有序!

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


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

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

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

Sample Input
3 31 2 40 0
 

Sample Output
1 2 3 4
 

import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNext()) {int n = scanner.nextInt();int m = scanner.nextInt();if (n == 0 && m == 0) {return;}int[] sequence = new int[n + 1];for (int i = 0; i < n; i++) {sequence[i] = scanner.nextInt();}// 找出m应在的数组下标int index = n;for (int i = 0; i < n; i++) {if (sequence[i] > m) {index = i;break;}}// 把m插入到数组中for (int i = n; i > index; i--) {sequence[i] = sequence[i - 1];}sequence[index] = m;for (int i = 0; i < n; i++) {System.out.print(sequence[i] + " ");}System.out.println(sequence[n]);}}}
0 0
原创粉丝点击