ural 1656. Far Away Kingdom's Army(bfs)

題意:有一個方陣有n行n列(3<=n<=9),共有n*n個人。現在已知他們的身高爲170~200釐米之間。

求一種可行的方案將他們排在方陣中,使得同一行、同一列中,高度總是從中間向兩邊遞減

解法:對輸入的數據從大往小遍歷,對矩陣從中央開始進行bfs即可。貌似是桶排序。

#include <iostream>
#include <queue>
using namespace std;

const int mov[4][2]={0,1,0,-1,1,0,-1,0};
int n,tot,arr[201]={0},ans[10][10]={0};

struct node
{
   int x,y;
   node(){x=y=0;}
}u,v;

int get()
{
    while((!arr[tot])&&tot)
     --tot;
    --arr[tot];
    return tot;
}

int main()
{
    queue<node> q;
    cin>>n;
    for (int i=n*n;i;--i)
    {
        cin >> tot;
        ++arr[tot];
    }
    tot=200;
    node tmp;
    tmp.x=(n+1)/2;
    tmp.y=(n+1)/2;
    ans[(n+1)/2][(n+1)/2]=get();
    q.push(tmp);
    while(!q.empty())
    {
        u=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            v.x=u.x+mov[i][0];
            v.y=u.y+mov[i][1];
            if ((v.x < 1) || (v.y < 1) || (v.x > n) || (v.y > n))
                continue;
            if (ans[v.y][v.x])  continue;
            ans[v.y][v.x]=get();
            q.push(v);
        }
    }
    for (int i=1;i<=n;++i)
    {
        for (int j=1;j<=n;++j)
            cout << ans[i][j] << ' ';
        cout << endl;
    }
    cin>>n;
    return 0;
}
            


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章