您的位置:首页 > 其它

【PAT】1035. 插入与归并(25)

2016-02-27 00:15 330 查看
插入与归并(25)

时间限制

200 ms

内存限制

65536 kB

代码长度限制

8000 B

判题程序

Standard

作者

CHEN, Yue

根据维基百科的定义:

插入排序是迭代算法,逐一获得输入数据,逐步产生有序的输出序列。每步迭代中,算法从输入序列中取出一元素,将之插入有序序列中正确的位置。如此迭代直到全部元素有序。

归并排序进行如下迭代操作:首先将原始序列看成N个只包含1个元素的有序子序列,然后每次迭代归并两个相邻的有序子序列,直到最后只剩下1个有序的序列。

现给定原始序列和由某排序算法产生的中间序列,请你判断该算法究竟是哪种排序算法?

输入格式:

输入在第一行给出正整数N (<=100);随后一行给出原始序列的N个整数;最后一行给出由某排序算法产生的中间序列。这里假设排序的目标序列是升序。数字间以空格分隔。

输出格式:

首先在第1行中输出“Insertion Sort”表示插入排序、或“Merge Sort”表示归并排序;然后在第2行中输出用该排序算法再迭代一轮的结果序列。题目保证每组测试的结果是唯一的。数字间以空格分隔,且行末不得有多余空格。

输入样例1:

10

3 1 2 8 7 5 9 4 6 0

1 2 3 7 8 5 9 4 6 0

输出样例1:

Insertion Sort

1 2 3 5 7 8 9 4 6 0

输入样例2:

10

3 1 2 8 7 5 9 4 0 6

1 3 2 8 5 7 4 9 0 6

输出样例2:

Merge Sort

1 2 3 8 4 5 7 9 0 6

运行超时,啊啊啊

#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include <cstdio>
//#include <cstdlib>
#include <algorithm>

using namespace std;

bool issorted(int *ad,int begin,int end) {
int i = begin+1;
while (i != end) {
if (ad[i] < ad[i-1]) {
return false;
}
i++;
}
return true;
}

void printList(int * list,int n) {
for (int i = 0; i < n; i++) {
cout << list[i];
}
}

int main() {
freopen("input.txt", "r", stdin);

int n;
scanf("%d", &n);
int *numList = (int*)malloc(n*sizeof(int));
int *orgList = (int*)malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d", &orgList[i]);
}
bool flag = true;
int temp_num = -1;
int sorted_length;
for (int i = 0; i < n; i++) {
scanf("%d", &numList[i]);
if (flag && numList[i] < temp_num) {
flag = false;
sorted_length = i;
}
else {
temp_num = numList[i];
}
}
sort(orgList, orgList + sorted_length);
//printList(orgList, n);
flag = true;
for (int i = 0; i < n; i++) {
if (numList[i] != orgList[i]) {
flag = false;
break;
}
}
//true insert        false->归并排序
if (flag) {
sort(numList, numList + sorted_length + 1);
cout << "Insertion Sort\n";
}else {
cout << "Merge Sort\n";
bool find_length_tag = false;   //是否找到堆排序的长度
while (sorted_length>2) {
int k = n / sorted_length;
bool issortedflag = true;
for (int i = 0; i < k; i++) {
if (issorted(numList, i*sorted_length, (i + 1)*sorted_length) == false) {
issortedflag = false;
}
}
if (n%sorted_length != 0) {
if (issorted(numList, k*sorted_length, n) == false) {
issortedflag = false;
}
}
if (issortedflag) { //如果这个长度都是有序的话s
break;
}
else {
if (sorted_length / 2 >= 2) {
sorted_length = sorted_length / 2;
}
else {
sorted_length = 2;
}
}
}
sorted_length = sorted_length * 2;
//开始排序下一轮
int k = n / sorted_length;
for (int i = 0; i < k; i++) {
sort(numList + i*sorted_length, numList + (i + 1)*sorted_length);
}
if (n%sorted_length != 0) {
sort(numList + sorted_length*k, numList + n);
}
}
for (int i = 0; i < n; i++) {
cout << numList[i];
if (i != n - 1) {
cout << " ";
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: