SSU 479.Funny Feature

来源:互联网 发布:java填空题 编辑:程序博客网 时间:2024/06/07 06:42

给个BNU的原题链接:http://www.bnuoj.com/bnuoj/problem_show.php?pid=10686

题意大概是在一个n * m的矩阵里,你依次往不同的坐标处放种子,放完种子之后,它和它的上下左右如果有种子,在下一回合就会生出一个果实。

PS:每个位置都要放种子,直到所有位置都放过一次之后停止

然后现在输入每个位置的最终的果实个数,输出你是如何依次放的种子。

如果从结果往回推的话,实际上我们可以找到果实数为“1”的位置,这将是最后一回合所放种子的位置,因为只有最后放了这个种子,它自身才能在下一回生出一个果实。然后我们将它,以及它的上下左右都减1,即回退到上一个回合,这样我们再找下一个“1”,依次操作,最终即可得到结果。

这里我采用的是用队列存储果实数为“1”的节点,用栈来存储最后被放果实的节点便于正序输出结果。

#include <iostream>#include <cstdio>#include <queue>#include <stack>#include <algorithm>using namespace std;int n, m;int map[205][205];int dir[4][2] = {0, -1, 0, 1, -1, 0, 1, 0};bool judge[205][205];class node {public:    int x, y;    void print() {        printf("%d %d\n", x, y);    }};void init() {    for(int i = 0; i <= n + 1; i++) {        for(int j = 0; j <= m; j++) {            map[i][j] = -1;            judge[i][j] = false;        }    }}int main() {    loop: while(~scanf("%d%d", &n, &m)) {        queue<node> q;        stack<node> s;        init();        for(int i = 1; i <= n; i++) {            for(int j = 1; j <= m; j++) {                scanf("%d", &map[i][j]);                if(map[i][j] == 1){                    node xi;                    xi.x = i, xi.y = j;                    q.push(xi);                }            }        }        while(!q.empty()) {            node next = q.front();            q.pop();            s.push(next);            judge[next.x][next.y] = true;            for(int i = 0; i < 4; i++){                int x = next.x + dir[i][0];                int y = next.y + dir[i][1];                if(judge[x][y] == false && map[x][y] != -1){                    map[x][y]--;                    if(map[x][y] == 1){                        node xi;                        xi.x = x, xi.y = y;                        q.push(xi);                    }                    else if(map[x][y] == 0){                        printf("No solution\n");                        goto loop;                    }                }            }        }        if(s.size() != n * m){            printf("No solution\n");            goto loop;        }        while(!s.empty()){            s.top().print();            s.pop();        }    }    return 0;}


0 0