浙江大学计算机与软件学院 2019 年保研机考 7-2 Zigzag Sequence (C++)

This time your job is to output a sequence of N N N positive integers in a zigzag format with width M M M in non-decreasing order. A zigzag format is to fill in the first row with M M M numbers from left to right, then the second row from right to left, and so on and so forth. For example, a zigzag format with width 5 for numbers 1 to 13 is the following:

1 2 3 4 5
10 9 8 7 6
11 12 13

Input Specification:

Each input file contains one test case. For each case, the first line gives 2 positive integers N N N and M M M. Then the next line contains N N N positive integers as the original sequence. All the numbers are no more than 1 0 4 10^4 104. The numbers in a line are separated by spaces.

Output Specification:

For each test case, output the sequence in the zigzag format with width M M M in non-decreasing order. There must be exactly 1 space between two adjacent numbers, and no extra space at the beginning or the end of each line.

Sample Input 1:

14 5
37 76 98 20 98 76 42 53 99 95 60 81 58 93

Sample Output 1:

20 37 42 53 58
93 81 76 76 60
95 98 98 99

Sample Input 2:

15 4
96 37 76 98 20 98 76 42 53 99 95 60 81 58 93

Sample Output 2:

20 37 42 53
76 76 60 58
81 93 95 96
99 98 98

Solution:

// Talk is cheap, show me the code
// Created by Misdirection 2021-09-19 19:03:13
// All rights reserved.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int nums[10010];

int main(){
    int n, m;
    scanf("%d %d", &n, &m);

    for(int i = 0; i < n; ++i) scanf("%d", &nums[i]);
    sort(nums, nums + n);

    int row = n / m;
    for(int i = 0; i < row; ++i){
        if(i % 2 == 0){
            for(int j = 0; j < m; ++j){
                if(j == m - 1) printf("%d\n", nums[m * i + j]);
                else printf("%d ", nums[m * i + j]);
            }
        }
        else{
            for(int j = 0; j < m; ++j){
                if(j == m - 1) printf("%d\n", nums[(i + 1) * m - j - 1]);
                else printf("%d ", nums[(i + 1) * m - j - 1]);
            }
        }
    }

    if(m * row != n){
        int left = n - m * row;

        if(row % 2 == 0){
            for(int i = left - 1; i >= 0; --i){
                if(i == 0) printf("%d\n", nums[n - i - 1]);
                else printf("%d ", nums[n - i - 1]);
            }
        }
        else{
            for(int i = 0; i < left; ++i){
                if(i == left - 1) printf("%d\n", nums[n - i - 1]);
                else printf("%d ", nums[n - i - 1]);
            }
        }
    }

    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

负反馈循环

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值