• PAT(Advanced Level)A1098.Insertion or Heap Sort


    题意

    给定一个序列和几次迭代后的序列,问能否判断出是属于插入排序or堆排序。要求判断后输出对应方法的下一次迭代的序列

    思路

    • 区分插入排序和归并排序的要点在于:插入排序总是会使得前几个元素有序,而堆排序是后几个有序,而且堆本身是左小右大,所以我们只要比较前2个元素的大小关系就知道是哪一种了
    • 插入排序的下一次迭代就是让前面的有序小区间长度+1,所以找到第一个不符合有序的定义来处理就好,这里可以用sort()函数少写点代码

    代码

    #include <cstdio>
    #include <vector>
    #include <algorithm>
    #include <iostream>
    using namespace std;
    const int MAXN = 110;
    int heap[MAXN];     //存储第二个序列
    int N;
    int origin[MAXN];
    void insert_sort(int a[])
    {
        int pos = 1;
        for(int i=1;i<=N;i++)
        {
            if(a[i] > a[i+1])
            {
                pos = i + 1;
                break;
            }
        }
        sort(a + 1, a + pos + 1);
    }//插入排序
    void downAdjust(int heap[], int low, int high)
    {
        int i = low, j = i * 2;
        while(j <= high)
        {
            if(j + 1 <= high && heap[j + 1] > heap[j])
                j = j + 1;
            if(heap[j] > heap[i])
            {
                swap(heap[j], heap[i]);
                i = j;
                j = i * 2;
            }else break;
        }
    }//向下调整
    void heap_sort(int heap[])
    {
        int pos = 1;
        for(int i=N;i>=1;i--)
            if(heap[i] < heap[1])
            {
                pos = i;
                swap(heap[1], heap[pos]);
                break;
            }
        downAdjust(heap, 1, pos - 1);
    }//堆排序
    int main()
    {
        cin >> N;
        for(int i=1;i<=N;i++)    cin >> origin[i];
        for(int i=1;i<=N;i++)    cin >> heap[i];
        if(heap[1] < heap[2])   //插入排序
        {
            insert_sort(heap);
            cout << "Insertion Sort
    ";
            for(int i=1;i<=N;i++)
                i == N ? cout << heap[i] : cout << heap[i] << " ";
        }else{
            heap_sort(heap);
            cout << "Heap Sort
    ";
            for(int i=1;i<=N;i++)
                i == N ? cout << heap[i] : cout << heap[i] << " ";
        }
        return 0;
    }
    
    
  • 相关阅读:
    2017ICPC南宁补题
    H. The Game of Life
    I
    Twice Equation
    (贪心+队列)String
    Marcin and Training Camp
    莫比乌斯函数模版
    HDU-1695 莫比乌斯反演
    Steps to One DP+莫比乌斯反演
    Educational Codeforces Round 62 (Rated for Div. 2)
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/13907091.html
Copyright © 2020-2023  润新知