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

来源:互联网 发布:淘宝旺铺收费 编辑:程序博客网 时间:2024/05/23 11:48
题意:有一个方阵有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;}            


原创粉丝点击