AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 校园
  • 应用
  • 文章
    • 题解
    • 分享
    • 问答
  • 吐槽
  • 登录/注册

AcWing 1579. 插入还是归并    原题链接    中等

作者: 作者的头像   华胥梦断 ,  2022-06-24 10:55:29 ,  所有人可见 ,  阅读 12


0


参考了:https://www.acwing.com/activity/content/code/content/323536/ 和 https://www.acwing.com/activity/content/code/content/272766/

C++ 代码

#include<bits/stdc++.h>
using namespace std;

const int N = 110;
int a[N], b[N];
int n =0;

bool check()
{
    for(int i = 1; i <=n; ++i)
        if(a[i] != b[i])
            return false;
    return true;
}


int main()
{
    cin >> n;
    for(int i=1; i <= n; ++i) cin >> a[i];
    for(int i = 1; i <=n; ++i) cin >> b[i];

    int p=2;
    while(p <=n && b[p] >= b[p-1]) ++p;

    int pos = p;
    while(p<= n && a[p] == b[p]) ++p;

    if(p == n+1) //插入排序
    {
        puts("Insertion Sort");
        p = pos;
        while(p>1 && b[p]<  b[p-1])
            swap(b[p],b[p-1]),--p;
        for(int i=1; i<=n; ++i)
        {
            cout << b[i];
            if(i < n)
                cout << ' ';
        }
    }
    else //归并排序
    {
        puts("Merge Sort");

        int k = 1;
        while(true)
        {
            bool match = check();
            int len = 1 << k;
            for(int i = 1; i <= n; i+=len)
            {
                sort(a+i,a+min(n+1,i+len));
            }
            if(match)
                break;
            ++k;
        }

        for(int i=1; i<=n; ++i)
        {
            cout << a[i];
            if(i < n)
                cout << ' ';
        }
    }

    return 0;
}

0 评论

你确定删除吗?

© 2018-2022 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息