This time your job is to output a sequence of N positive integers in a zigzag format with width M in non-decreasing order. A zigzag format is to fill in the first row with 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 and M. Then the next line contains N positive integers as the original sequence. All the numbers are no more than 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 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
分析:快乐模拟
解决:
1、遍历数组,按mod输出。
2、注意点:最后一行不足满列时的输出特别注意,如
5 3
1 2 3 4 51 2 3
5 4
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int n,m;
cin>>n>>m;
vector<int> arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
sort(arr.begin(),arr.end());
int row = 0,count = 0,f=0;
for(int i=0;i<n;i++){
if(i%m!=0) cout<<" ";
if((i/m)%2==0){
cout<<arr[i];
f=0;
count = i;
}
else{
if(count+m-f<n) cout<<arr[count+m-f];
else i--;
f++;
}
row++;
if(row==m) {
printf("\n");
row=0;
}
}
return 0;
}