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;
}