题目大意:给出N个数的序列以及某次排序后的序列,判断它是插入排序还是归并排序的结果,并输出下一次排序的结果。
考察插入排序的写法和归并排序的非递归写法,直接进行两种排序的模拟,如果等于排序后的序列,那么输出下一次排序后的结果。
AC代码:
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
bool judgeInsert(const vector<int> &v, vector<int> &partSorted)
{
vector<int> tmp = v;
bool flag = false;
for (int i = 1; i < v.size(); ++i)
{
int value = tmp[i];
int j;
for (j = i; j > 0 && tmp[j-1] > value; --j)
tmp[j] = tmp[j-1];
tmp[j] = value;
if(flag)
{
printf("Insertion Sort\n");
for (int k = 0; k < tmp.size(); ++k)
{
printf("%d", tmp[k]);
if(k < tmp.size() - 1) printf(" ");
}
return true;
}
if(tmp == partSorted)
flag = true;
}
return false;
}
void merge(vector<int> &v, int left, int mid, int right)
{
vector<int> tmp(right - left + 1);
int i = left, j = mid + 1, k = 0;
while(i <= mid && j <= right)
{
if(v[i] <= v[j]) tmp[k++] = v[i++];
else tmp[k++] = v[j++];
}
while(i <= mid) tmp[k++] = v[i++];
while(j <= right) tmp[k++] = v[j++];
for (int l = left; l <= right; ++l)
v[l] = tmp[l-left];
}
bool judgeMerge(const vector<int> &v, vector<int> &partSorted)
{
vector<int> tmp = v;
int n = tmp.size();
bool flag = false;
for (int sz = 1; sz < tmp.size(); sz += sz)
{
for (int i = 0; i + sz< n; i += sz * 2)
merge(tmp,i, i+sz-1, min(i + 2 * sz-1, n - 1));
if(flag)
{
printf("Merge Sort\n");
for (int i = 0; i < tmp.size(); ++i)
{
printf("%d", tmp[i]);
if(i < tmp.size() - 1) printf(" ");
}
return true;
}
if(tmp == partSorted) flag = true;
}
return false;
}
int main()
{
int N;
scanf("%d", &N);
vector<int> v(N), partSorted(N);
for (int i = 0; i < N; ++i)
scanf("%d", &v[i]);
for (int i = 0; i < N; ++i)
scanf("%d", &partSorted[i]);
if(!judgeInsert(v, partSorted))
judgeMerge(v, partSorted);
return 0;
}