See the article on https://dyingdown.github.io/2019/12/20/HDU-2019%20Ordered-Sequence/
Ordered Sequence
There are n (n <= 100) integers, which have been arranged in ascending order. Now give another integer x, please insert the number into the sequence and keep the new sequence still ordered.
Input
The input data contains multiple test cases. Each set of data consists of two rows, the first row is n and m, and the second row is a sequence of n numbers that have been ordered. n and m are 0 at the same time to mark the end of the input data, this line does not do processing.
Output
For each test case, output the sequence after inserting the new element.
Sample Input
3 3
1 2 4
0 0
Sample Output
1 2 3 4
Analysis
Using C++ Sort.
Code
#include<bits/stdc++.h>
using namespace std;
int arr[1000];
int main() {
int n, m;
while(cin >> n >> m, n, m){
for(int i = 0; i < n; i ++) {
cin >> arr[i];
}
arr[n] = m;
sort(arr, arr + n + 1);
for(int i = 0; i <= n; i ++) {
if(i == n) cout << arr[i] << endl;
else cout << arr[i] << " ";
}
}
return 0;
}
本文介绍了一个简单的算法,用于将一个整数插入到已排序的序列中,并保持序列的有序状态。通过C++的sort函数实现,适用于处理多组测试数据。输入包含多个测试案例,每个案例由一个序列和一个待插入的整数组成,输出则是插入新元素后的有序序列。
6万+

被折叠的 条评论
为什么被折叠?



