题解:P2493 [SDOI2011] 贪食蛇

· · 题解

P2493 [SDOI2011] 贪食蛇 题解

思路分析

本题是一个典型的状态压缩最短路问题。我们需要控制一条蛇在网格中移动,吃掉所有食物,且要求总时间最短。由于边权(时间消耗)不为 1,应使用 ‌Dijkstra 算法‌(优先队列 BFS)。

1. 状态表示

蛇的状态由以下三部分组成:

  1. ‌已吃食物集合‌:N \le 4,可以用一个 4 位的二进制掩码 mask 表示。
  2. ‌蛇的形态‌:
    • 蛇的初始长度为 4,每吃一个食物长度加 1,最大长度为 4+4=8。
    • 网格大小 R, C \le 12,每个坐标 (r, c) 可以压缩为一个 8 位整数:code = (r \ll 4) | c。
    • 蛇身最多 8 节,总共需要 8 \times 8 = 64 位,正好可以用一个 unsigned long long 存储。
    • ‌编码规则‌:将蛇身从尾到头依次存入 ULL 的低字节到高字节。即最低 8 位存蛇尾,最高有效字节存蛇头,方便通过位移操作获取头尾和生成新状态。
  3. ‌当前时间‌:用于 Dijkstra 的优先级排序。

2. 状态转移

对于当前状态,尝试向四个方向(上、下、左、右)移动:

  1. ‌基本检查‌:新位置必须在界内且非障碍物(权值 >0)。
  2. ‌判断是否进食‌:检查新位置是否有未吃的食物。
  3. ‌碰撞检测‌:
    • ‌若进食‌:蛇长 +1,蛇尾不动。新头部不能与当前蛇身的‌任何‌部分重合。
    • ‌若不进食‌:蛇长不变,蛇尾移走。新头部不能与当前蛇身‌除蛇尾外‌的任何部分重合(因为蛇尾即将离开,头可以走到原尾巴的位置)。
  4. ‌计算代价‌:时间增加 |w_{\text{old}} - w_{\text{new}}| + 1。
  5. ‌更新状态‌:
    • 更新 mask。
    • 更新 body:移除旧尾(如果不进食),在高位加入新头。

3. 路径记录

使用 map<StateKey, pair<StateKey, char>> 记录每个状态的前驱状态和移动方向。找到终点后,从终点回溯到起点,反转字符串即可得到操作序列。

代码实现

95pts


#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <algorithm>
#include <map>
#include <cmath>

using namespace std;

int dr[] = {-1, 1, 0, 0};
int dc[] = {0, 0, -1, 1};
char dir_char[] = {'U', 'D', 'L', 'R'};

int R, C;
int grid[15][15];
int foods[5][2];
int N;

inline int encode(int r, int c) {
    return (r << 4) | c;
}

inline int decode_r(int code) { return code >> 4; }
inline int decode_c(int code) { return code & 0xF; }

struct State {
    int time;
    int mask; 
    unsigned long long body; 

    bool operator>(const State& other) const {
        return time > other.time;
    }
};

typedef pair<int, unsigned long long> StateKey;
map<StateKey, pair<StateKey, char>> pre;

int get_head_code(unsigned long long body, int len) {
    int shift = (len - 1) * 8;
    return (body >> shift) & 0xFF;
}

unsigned long long get_new_body(unsigned long long old_b, int old_len, int new_head_code, bool eat) {
    int keep_len = eat ? old_len : old_len - 1;
    unsigned long long rem = old_b >> (eat ? 0 : 8);
    unsigned long long new_b = rem | ((unsigned long long)new_head_code << (keep_len * 8));
    return new_b;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    cin >> R >> C;
    for (int i = 0; i < R; ++i) {
        string row;
        cin >> row;
        for (int j = 0; j < C; ++j) {
            grid[i][j] = row[j] - '0';
        }
    }

    vector<pair<int,int>> init_pos(4);
    for (int i = 0; i < 4; ++i) {
        cin >> init_pos[i].first >> init_pos[i].second;
        init_pos[i].first--;
        init_pos[i].second--;
    }

    cin >> N;
    for (int i = 0; i < N; ++i) {
        cin >> foods[i][0] >> foods[i][1];
        foods[i][0]--;
        foods[i][1]--;
    }

    unsigned long long start_body = 0;
    for (int i = 0; i < 4; ++i) {
        int code = encode(init_pos[i].first, init_pos[i].second);
        start_body = (start_body << 8) | code;
    }

    int start_mask = 0;
    priority_queue<State, vector<State>, greater<State>> pq;
    map<StateKey, int> dist;

    State start_s;
    start_s.time = 0;
    start_s.mask = start_mask;
    start_s.body = start_body;

    pq.push(start_s);
    dist[{start_mask, start_body}] = 0;

    vector<int> food_codes(N);
    for(int i=0; i<N; ++i) {
        food_codes[i] = encode(foods[i][0], foods[i][1]);
    }

    bool found = false;
    int final_time = -1;
    StateKey final_key;

    while (!pq.empty()) {
        State cur = pq.top();
        pq.pop();

        StateKey cur_key = {cur.mask, cur.body};
        if (dist.find(cur_key) == dist.end() || dist[cur_key] != cur.time) continue;

        if (cur.mask == (1 << N) - 1) {
            found = true;
            final_time = cur.time;
            final_key = cur_key;
            break;
        }

        int cur_len = 4 + __builtin_popcount(cur.mask);
        int head_code = get_head_code(cur.body, cur_len);
        int r = decode_r(head_code);
        int c = decode_c(head_code);
        int w_curr = grid[r][c];

        for (int d = 0; d < 4; ++d) {
            int nr = r + dr[d];
            int nc = c + dc[d];
            if (nr < 0 || nr >= R || nc < 0 || nc >= C) continue;
            if (grid[nr][nc] == 0) continue;

            int new_head_code = encode(nr, nc);
            int w_next = grid[nr][nc];
            int cost = abs(w_curr - w_next) + 1;

            bool will_eat = false;
            int food_idx = -1;
            for (int k = 0; k < N; ++k) {
                if ((cur.mask >> k) & 1) continue;
                if (food_codes[k] == new_head_code) {
                    will_eat = true;
                    food_idx = k;
                    break;
                }
            }

            vector<int> segs(cur_len);
            unsigned long long b_temp = cur.body;
            for(int k=0; k<cur_len; ++k) {
                segs[k] = b_temp & 0xFF;
                b_temp >>= 8;
            }

            bool collision = false;
            if (will_eat) {
                for (int k = 0; k < cur_len; ++k) {
                    if (segs[k] == new_head_code) {
                        collision = true;
                        break;
                    }
                }
            } else {
                for (int k = 1; k < cur_len; ++k) {
                    if (segs[k] == new_head_code) {
                        collision = true;
                        break;
                    }
                }
            }

            if (collision) continue;

            int new_mask = cur.mask;
            if (will_eat) new_mask |= (1 << food_idx);

            unsigned long long new_body = get_new_body(cur.body, cur_len, new_head_code, will_eat);
            StateKey next_key = {new_mask, new_body};
            int new_time = cur.time + cost;

            if (dist.find(next_key) == dist.end() || dist[next_key] > new_time) {
                dist[next_key] = new_time;
                pre[next_key] = {cur_key, dir_char[d]};

                State next_s;
                next_s.time = new_time;
                next_s.mask = new_mask;
                next_s.body = new_body;
                pq.push(next_s);
            }
        }
    }

    if (!found) {
        cout << "No solution." << endl;
    } else {
        cout << final_time << endl;
        string path = "";
        StateKey k = final_key;
        while (pre.find(k) != pre.end()) {
            path += pre[k].second;
            k = pre[k].first;
        }
        reverse(path.begin(), path.end());
        cout << path << endl;
    }
    return 0;
}