1105. Spiral Matrix (25) -- 模拟

来源:互联网 发布:奥拉迪波体测数据 编辑:程序博客网 时间:2024/05/09 06:54

题目地址

https://www.patest.cn/contests/pat-a-practise/1105

ac代码

思路是:外围转一圈的函数封装起来,然后遍历填充,注意判断是否完成了

#include <cstdio>#include <cstdlib>#include <cmath>#include <cstring>#include <iostream>#include <string>#include <vector>#include <queue>#include <algorithm>#include <sstream>#include <list>#include <stack> #include <map> #include <set> #include <iterator> #include <unordered_map>using namespace std;#define INF 0x7ffffffftypedef long long int LL;const int N = 404;int n;vector<int> v;bool cmp(int a, int b){    return a > b;}int r;int c;vector<vector<int>> ans;void func(int stai,int staj,int endi,int endj,int index){    if(stai == endi) // 只有一行    {        for(int j=staj;j<=endj;j++){            ans[stai][j] = v[index++];            if(index > n)                break;        }        return;    }    if(staj == endj) // 只有一列    {        for(int i=stai;i<=endi;i++){            ans[i][staj] = v[index++];            if(index > n)                break;        }        return;    }    for(int j=staj;j<=endj;j++){        ans[stai][j] = v[index++];        if(index > n)            break;    }    for(int i = stai + 1; i <= endi;i++)    {        ans[i][endj] = v[index++];        if(index > n)            break;    }    for(int j = endj - 1; j >= staj ; j--)    {        ans[endi][j] = v[index++];        if(index > n)            break;    }    for(int i= endi - 1;i>=stai+1;i--)    {        ans[i][staj] = v[index++];        if(index > n)            break;    }}int main(){    //freopen("in.txt", "r" , stdin);    while(scanf("%d", &n) != EOF)    {        for(int i=0;i<n;i++)        {            int tmp;            scanf("%d", &tmp);            v.push_back(tmp);        }        sort(v.begin(), v.end(), cmp);        r = n;        c = 1;        int cha = r - c;        for(int i=1;i<=n;i++)        {            for(int j=1;j<=i;j++)            {                if(i * j == n)                {                    if(i - j < cha)                    {                        r = i;                        c = j;                        cha = i - j;                    }                }            }        }        vector<vector<int>> ansT(r, vector<int>(c));        ans = ansT;        int stai = 0;        int endi = r - 1;        int staj = 0;        int endj = c - 1;        int index = 0;        while(index < n)        {            int cnt = 2 * (endj - staj + 1) + 2 * (endi - stai + 1 - 2);            func(stai, staj, endi, endj, index);            index += cnt;            stai ++;            staj ++;            endi --;            endj --;        }        for(int i=0;i<r;i++)        {            cout << ans[i][0];            for(int j=1;j<c;j++)            {                cout << " " << ans[i][j];            }            cout << endl;        }    }    return 0;}
0 0
原创粉丝点击