浙大保研2019年上机题 7-2 Zigzag Sequence (25分)

Posted littlepage

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浙大保研2019年上机题 7-2 Zigzag Sequence (25分)相关的知识,希望对你有一定的参考价值。

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

交叉数字,我们采用进行交叉的方法,进行打印数字,例如,15 4,则输入15个数字,4个数字4个数字输出,从0开始,每奇数行进行翻转打印即可。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void output(vector<int>& v) {
   printf("%d", v[0]);
   for(int i = 1; i < v.size(); i++)
       printf(" %d", v[i]);
   putchar(‘
‘);
}
int main() {
   // freopen("in.txt", "r", stdin);
   // freopen("out.txt", "w", stdout);
   int N, M;
   scanf("%d%d", &N, &M);
   vector<int> v(N), tmp;
   for(int i = 0; i < N; i++)
       scanf("%d", &v[i]);
   sort(v.begin(), v.end());
   vector<vector<int>> ans;
   for(int i = 0; i < N; i++) {
       tmp.push_back(v[i]);
       if(tmp.size() == M) {
           if(ans.size() % 2 == 1) 
               reverse(tmp.begin(), tmp.end());
           ans.push_back(tmp);
           tmp.clear();
       }
   }
   if(tmp.size() != 0) {
       if(ans.size() % 2 == 1) 
               reverse(tmp.begin(), tmp.end());
       ans.push_back(tmp);
   }
   for(int i = 0; i < ans.size(); i++)
       output(ans[i]);
   return 0;
}

以上是关于浙大保研2019年上机题 7-2 Zigzag Sequence (25分)的主要内容,如果未能解决你的问题,请参考以下文章

浙大保研2019年上机题 7-4 Index of Popularity (30分)

浙大保研2019年上机题 7-3 Is It An AVL Tree (25分)

考研上机水题整理——浙大2006

天大软工保研经验分享

天大软工保研考试经验分享

我的2019计算机保研经历(浙大哈工深中南)