现在的位置: 首页 > 综合 > 正文

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

2012年12月16日 ⁄ 综合 ⁄ 共 799字 ⁄ 字号 评论关闭

题意:有一个方阵有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;
}
            
【上篇】
【下篇】

抱歉!评论已关闭.