首页 > 代码库 > ZJU PAT 1089
ZJU PAT 1089
注意到数据规模比较小(N<=100),因此采用了投机取巧的办法:调用sort函数进行排序,而不是真正地做插入排序和归并排序
另一个需要注意的地方是,当检测到数列与所给数列相同之后,要在下一次发生insertion时,也就是当数列发生了改变时,才输出
//当检测到数列与所给数列相同之后,要在下一次发生insertion时,也就是当数列发生了改变时,才输出#include <iostream>#include <algorithm>#include <vector>using namespace std;int n;bool compare(vector<int> a, vector<int> b) { for (int i = 0; i != n; ++i) { if (a[i] != b[i]) { return false; } } return true;}void print(vector<int> a) { for (int i = 0; i != n - 1; ++i) { printf("%d ", a[i]); } printf("%d\n", a[n - 1]);}bool doInsert(vector<int> in, vector<int> re) { vector<int>::iterator it1 = in.begin(); vector<int>::iterator it2 = in.begin(); bool find = false; for (; it2 != in.end();) { if (!find && compare(in, re)) { printf("Insertion Sort\n"); find = true; } advance(it2, 1); sort(it1, it2); if (find && !compare(in, re)) { print(in); return true; } } return false;}void doMerge(vector<int> me, vector<int> re) { int k = (int)(log(n*1.0) / log(2.0)); bool find = false; for (int i = 0, step = 2; i != k; ++i, step *= 2) { if (!find && compare(me, re)) { printf("Merge Sort\n"); find = true; } vector<int>::iterator it1 = me.begin(); vector<int>::iterator it2; for (int j = 0; j != n / step; ++j) { if (j != 0) { advance(it1, step); } it2 = it1; advance(it2, step); sort(it1, it2); } if (it2 != me.end()) { sort(it2, me.end()); } if (find && !compare(me, re)) { print(me); return; } } sort(me.begin(), me.end()); print(me);}int main() { scanf("%d", &n); vector<int> in, me, re; int num; for (int i = 0; i != n; ++i) { scanf("%d", &num); in.push_back(num); me.push_back(num); } for (int i = 0; i != n; ++i) { scanf("%d", &num); re.push_back(num); } if (doInsert(in, re)) { return 0; } doMerge(me, re); return 0;}
ZJU PAT 1089
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。