zoukankan      html  css  js  c++  java
  • 1105 Spiral Matrix (25分)

    This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrix is filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and n columns, where m and n satisfy the following: m×n must be equal to N; mn; and mn is the minimum of all the possible values.

    Input Specification:

    Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains N positive integers to be filled into the spiral matrix. All the numbers are no more than 1. The numbers in a line are separated by spaces.

    Output Specification:

    For each test case, output the resulting matrix in m lines, each contains n numbers. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.

    Sample Input:

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

    Sample Output:

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

    排序后利用一个dir进行上下左右的方向切换即可。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    int N;
    int main() {
        scanf("%d", &N);
        vector<int> v(N);
        for(int i = 0; i < N; i++)
            scanf("%d", &v[i]);
        sort(v.begin(), v.end(), greater<int>());
        int col, row;
        for(int i = 1; i * i <= N; i++)
            if(N % i == 0) col = i;
        row = N / col;
        vector<vector<int>> ans(row);
        for(int i = 0; i < row; i++) ans[i].resize(col, -1);
        int x = 0, y = 0, dir = 0, i = 0;// 0 右边 1 下面 2 左面 3 上面
        if(y + 1 >= col || ans[x][y + 1] != -1) dir = (dir + 1) % 4; // 开始方向可能朝下
        while(true) {
            if(i == v.size()) break;
            if(dir == 0) {
                ans[x][y++] = v[i++]; 
                if(y + 1 >= col || ans[x][y + 1] != -1) dir = (dir + 1) % 4;
            } else if(dir == 1) {
                ans[x++][y] = v[i++];
                if(x + 1 >= row || ans[x + 1][y] != -1) dir = (dir + 1) % 4;
            } else if(dir == 2) {
                ans[x][y--] = v[i++];
                if(y - 1 < 0 || ans[x][y - 1] != -1) dir = (dir + 1) % 4;
            } else {
                ans[x--][y] = v[i++];
                if(x - 1 < 0 || ans[x - 1][y] != -1) dir = (dir + 1) % 4;
            }
        }
        for(int i = 0; i < row; i++) {
            printf("%d", ans[i][0]);
            for(int j = 1; j < col; j++) 
                printf(" %d", ans[i][j]);
            putchar('
    ');
        }
        return 0;
    }
  • 相关阅读:
    接口测试-postman
    select
    SQLserver的七种约束。
    数据库的创建、表的创建。
    vim编辑器删除键失效
    客户端通过 HTTP 请求的 Header 信息总结
    清理/boot目录内容
    CentOS 7 配置samba 和 autofs
    CentOS 7 配置 nfs 和 autofs
    tftp简单文件传输协议基本配置
  • 原文地址:https://www.cnblogs.com/littlepage/p/12875957.html
Copyright © 2011-2022 走看看