zoukankan      html  css  js  c++  java
  • 排序3 Insertion or Heap Sort

    题目:https://pintia.cn/problem-sets/1268384564738605056/problems/1289169858763866114
    题解:https://www.liuchuo.net/archives/2273
    代码:

    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    void downAdjust(vector<int> &b, int low, int high) {
        int i = 1, j = i * 2;
        while(j <= high) {
            if(j + 1 <= high && b[j] < b[j + 1]) j = j + 1;
            if (b[i] >= b[j]) break;
            swap(b[i], b[j]);
            i = j; j = i * 2;
        }
    }
    int main() {
        int n, p = 2;
        scanf("%d", &n);
        vector<int> a(n + 1), b(n + 1);
        for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
        for(int i = 1; i <= n; i++) scanf("%d", &b[i]);
        while(p <= n && b[p - 1] <= b[p]) p++;
        int index = p;
        while(p <= n && a[p] == b[p]) p++;
        if(p == n + 1) {
            printf("Insertion Sort
    ");
            sort(b.begin() + 1, b.begin() + index + 1);
        } else {
            printf("Heap Sort
    ");
            p = n;
            while(p > 2 && b[p] >= b[1]) p--;
            swap(b[1], b[p]);
            downAdjust(b, 1, p - 1);
        }
        printf("%d", b[1]);
        for(int i = 2; i <= n; i++)
            printf(" %d", b[i]);
        return 0;
    }
  • 相关阅读:
    Java 测试代码模板
    git 保存用户名和密码
    git 高级命令
    git 最常用命令
    git 冲突解决
    git diff命令
    nginx静态服务器的配置
    使用SFTP工具下载文件
    git log 格式化输出
    9-angular.fromJson
  • 原文地址:https://www.cnblogs.com/simon-chou/p/13620107.html
Copyright © 2011-2022 走看看