浙江大学 计算机与软件学院 2019年保研 上机 模拟练习 7-2 Zigzag Sequence(25分)

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 10​4​​ . 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 5

1 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值