ACM篇:HDU 4771--Stealing Harry Potter‘s Precious

来源:互联网 发布:java双色球机选代码 编辑:程序博客网 时间:2024/06/05 01:51

状压宽搜。

#include <iostream>#include <cstdio>#include <cstring>#include <vector>#include <queue>using namespace std;int readchar(){    int ch;    while ((ch=getchar()) != '#' && ch != '.' && ch != '@')        ;    return ch;}const int MAX = 100;const int MAX_K = 4;struct Node{    int r;    int c;    Node(int r=0, int c=0)    {        this->r = r;        this->c = c;    }};struct Point{    int r;    int c;    int s;    Point(int r=0, int c=0, int s=0)    {        this->r = r;        this->c = c;        this->s = s;    }};bool maze[MAX+2][MAX+2];int step[MAX+2][MAX+2][1<<MAX_K];int n, m, k;vector<Node> precious;queue<Point> q;void read_maze(int *x, int *y){    for (int i = 1; i <= n; i++)        for (int j = 1; j <= m; j++)        {            int ch = readchar();            maze[i][j] = (ch == '#') ? false : true;            if (ch == '@')            {                *x = i;                *y = j;            }        }}void read_precious(){    int r, c;    precious.clear();    scanf("%d", &k);    for (int i = 0; i < k; i++)    {        scanf("%d%d", &r, &c);        precious.push_back(Node(r, c));    }}int is_precious(int nr, int nc){    for (int i = 0; i < k; i++)    {        if (precious[i].r == nr && precious[i].c == nc)            return i;    }    return -1;}bool in_maze(int r, int c){    return (r >= 1 && r <= n && c >= 1 && c <= m);}int _bfs(int r,int c){    static const int ROW[] = {0, 0, 1, -1};    static const int COL[] = {1, -1, 0, 0};    memset(step, -1, sizeof(step));    while (!q.empty())        q.pop();    step[r][c][0] = 0;    q.push(Point(r, c, 0));    while (!q.empty())    {        int index;        Point head = q.front();        if (head.s == (1<<k)-1)             return step[head.r][head.c][head.s];        q.pop();        for (int i = 0; i < 4; i++)        {            int nr = head.r + ROW[i];            int nc = head.c + COL[i];            int ns = head.s;            if (in_maze(nr, nc) && maze[nr][nc])            {                if((index = is_precious(nr, nc)) != -1)                    ns |= (1<<index);                if (step[nr][nc][ns] == -1)                {                    step[nr][nc][ns] = step[head.r][head.c][head.s] + 1;                    q.push(Point(nr, nc, ns));                }            }        }    }    return -1;}int main(){    int x, y;    while (scanf("%d%d", &n, &m) == 2 && n && m)    {        read_maze(&x, &y);        read_precious();        printf("%d\n", _bfs(x, y));    }    return 0;}
0 0
原创粉丝点击