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常规AC:#include <iostream> int main() { using namespace std; int n, m; while(cin >> n >> m &&(m||n)) { int * ptr = new int [n+1]; int j = n; for(int i=0; i<n; ++i) { cin >> ptr[i]; if(j==n && ptr[i]>m) j = i; } for(int i=n; i>j; --i) { ptr[i] = ptr[i-1]; } ptr[j] = m; for(int i=0; i<=n; ++i) { if(!i) cout << ptr[i]; else cout << " " << ptr[i]; } cout << endl; delete [] ptr; } return 0; }
尝试链表插入,果然时间上不一样啊~
Run ID | Submit Time | Judge Status | Pro.ID | Exe.Time | Exe.Memory | Code Len. | Language | Author |
2013-05-24 | Accepted | 2019 | 0MS | 292K | 1078 B | C++ | ||
2013-05-23 | Accepted | 2019 | 15MS | 344K | 664 B | G++ |
#include <iostream> //训练一下,更好地理解数据结构
struct node
{
int n;
node * ps;
};
node * CreatIn(int b);
int main()
{
using namespace std;
int n, m;
while(cin >> n >> m && (m||n))
{
node * fir = CreatIn(0);
node * ptr = fir;
node * mark = fir;
int j = 1;
for(int i=0; i<n; ++i)
{
int a;
cin >> a;
if(j && a>m)
j = 0;
ptr->ps = CreatIn(a);
ptr = ptr->ps;
if(j)
mark = ptr;
}
node * temp = mark->ps;
mark->ps = CreatIn(m);
mark->ps->ps = temp;
ptr = fir->ps;
delete fir;
while(ptr!=NULL)//非常讨厌的一点,现在C++11新标准已经支持nullptr为默认空字符了... 结果害得我几次CE,主要是被弄烦了
{
cout << ptr->n;
if(ptr->ps!=NULL)//我的IDE都能跑过,上OJ就CE ,次奥...
cout << " ";
node * m =ptr;
ptr = ptr->ps;
delete m;
}
cout << endl;
}
return 0;
}
node * CreatIn(int b)
{
node * ps = new node;
ps->n = b;
ps->ps = NULL;
return ps;
}