P16188 [ZJOI2014] 2048 の 题解

· · 题解

P16188 [ZJOI2014] 2048

闲话

在犇犇里看见这道题,觉得挺有意思的,遂尝试做了一下。

一开始觉得这题标黑虚高,但是实际写起来感觉还是很毒瘤的。

感觉这道题放在省选场切难度还是很大的,膜拜当年在场上切了 75 pts 的杜瑜皓老师。

真的不是我太菜了吗。

题意

2048 简化版,给定一随机数种子,每次会在一个随机的位置生成一个大小为 2 的瓦片,要求在若干次操作之后,合成大小为 32768 的瓦片。

提交答案,求每次的操作类型(L、R、U、U,即向左移动、向右移动、向上移动、向下移动)。

思路

考虑手玩 20 次 2048,记录一下游玩过程即可。太好了省选考场上还有 2048 玩。

由于本题是提交答案题,遂考虑深搜挂着机。

显然每次有 4 种可能的操作,操作 n 次最多有 4^n 种可能的情况,显然不可接受。

考虑启发式搜索,这里选择了束搜索。

::::info[束搜索]

束搜索,Beam Search,是常用于 LLM (Large Language Model)问题的一种启发式搜索方法。

其基本思想是,每次搜索时,向外扩展所有可能的节点,然后进行评估,选取得分最高的 k 个节点,作为下一轮搜索的起点。

其相较 IDA* 的优势在于,由于每次搜索时只扩展 k 个节点,所以搜索空间大大减小,提高了搜索效率。

考虑估值函数的设计,结合我们平时玩 2048 的经验,可以想到,每个状态的估值应该和大数字的位置、单调性和空格数量有关。

考虑为蛇形分布设计如下的权重:

\begin{matrix} 65536& 32768& 16384& 8192\\ 512& 1024& 2048& 4096\\ 256& 128& 64& 32\\ 2& 4& 8& 16\\ \end{matrix}

再加上如果不满足单调性,则给予扣分惩罚,再为空格的数量设计一个较大的权值(10^7),得到如下的估值函数:

LL F(const board &b){
    static const LL w[16] = {
        65536 , 32768 , 16384 , 8192 ,
          512 ,  1024 ,  2048 , 4096 ,
          256 ,   128 ,    64 ,   32 ,
            2 ,     4 ,     8 ,   16
    };
    LL res = 0;
    int empty = 0;
    for(int i = 0 ; i < 16 ; ++i){
        if(b.data[i] == 0)
            empty += 1;
        else
            res += (1LL << b.data[i]) * w[i];
    }
    LL mono = 0;
    for(int r = 0 ; r < 4 ; ++r){
        int lst = -1;
        for(int c = 0 ; c < 4 ; ++c){
            int val = b.data[r * 4 + c];
            if(val){
                if(lst != -1){
                    if(r == 0 || r == 2)
                        if(lst < val)
                            mono += (1LL << val);
                    else
                        if(lst > val)
                            mono += (1LL << lst);
                }
                lst = val;
            }
        }
    }
    for(int c = 0 ; c < 4 ; ++c){
        int lst = -1;
        for(int r = 0 ; r < 4 ; ++r){
            int val = b.data[r * 4 + c];
            if(val){
                if(lst != -1 && lst < val)
                    mono += (1LL << val);
                lst = val;
            }
        }
    }
    return res - mono * 8 + empty * 10000000LL;
}

有了估值函数,搜索显然。

值得一提的是,实际写代码的时候可以每次运行就调用一次题目附件中的 simulate(.exe) 进行验证,如果搜素失败,那么就增大 k 再次尝试。事实上,对于前两个测试点合成 4096 的要求,甚至 k=5 就足以解决这个问题。对于合成 32768 的要求,k=100 基本可以通过大部分测试点。

实测发现 k=500 时可以稳定合成 32768,通过所有测试点。

下附的代码中 K_values 作者经过多次测试,发现 5,25,100,500 的取值做到了测试次数少的同时获得较快的速度。

代码

::::info[code]

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned int UI;
typedef unsigned long long ULL;
//十年OI一场空,不开long long见祖宗
const int MUL = 8221;
int getRand(int &seq){
    int shifted = seq >> 16;
    UI useq = (UI)seq;
    useq = useq * (UI)MUL + (UI)shifted;
    seq = (int)useq;
    return seq & 15;
}
struct board{
    unsigned char data[16];
    board(){ memset(data , 0 , sizeof(data)); }
    bool operator==(const board &o) const{
        for(int i = 0 ; i < 16 ; ++i)
            if(data[i] != o.data[i])
                return false;
        return true;
    }
    ULL hash() const{
        ULL h = 0;
        for(int i = 0 ; i < 16 ; ++i)
            h = (h << 4) | data[i];
        return h;
    }
};
struct hash_{
    ULL operator()(const pair<ULL , int> &p) const{
        return hash<ULL>()(p.first) ^ (hash<int>()(p.second) << 1);
    }
};
bool moveL(board &b){
    bool moved = false;
    for(int r = 0 ; r < 4 ; ++r){
        int p = r * 4;
        unsigned char tmp[4] = {0};
        int idx = 0;
        for(int c = 0 ; c < 4 ; ++c)
            if(b.data[p + c])
                tmp[idx++] = b.data[p + c];
        for(int c = 0 ; c < 3 ; ++c){
            if(tmp[c] && tmp[c] == tmp[c + 1]){
                tmp[c] += 1;
                tmp[c + 1] = 0;
                c += 1;
            }
        }
        unsigned char temp[4] = {0};
        idx = 0;
        for(int c = 0 ; c < 4 ; ++c)
            if(tmp[c])
                temp[idx++] = tmp[c];
        for(int c = 0 ; c < 4 ; ++c){
            if(b.data[p + c] != temp[c])
                moved = true;
            b.data[p + c] = temp[c];
        }
    }
    return moved;
}
inline void reverse_(board &b){
    for(int r = 0 ; r < 4 ; ++r){
        swap(b.data[r * 4] , b.data[r * 4 + 3]);
        swap(b.data[r * 4 + 1] , b.data[r * 4 + 2]);
    }
}
bool moveR(board &b){
    reverse_(b);
    bool moved = moveL(b);
    reverse_(b);
    return moved;
}
inline void transpose(board &b){
    for(int r = 0 ; r < 4 ; ++r)
        for(int c = r + 1 ; c < 4 ; ++c)
            swap(b.data[r * 4 + c] , b.data[c * 4 + r]);
}
bool moveU(board &b){
    transpose(b);
    bool moved = moveL(b);
    transpose(b);
    return moved;
}
bool moveD(board &b){
    transpose(b);
    bool moved = moveR(b);
    transpose(b);
    return moved;
}
inline void add(board &b , int &cur_seq){
    while(true){
        int pos = getRand(cur_seq);
        if(b.data[pos] == 0){
            b.data[pos] = 1;
            break;
        }
    }
}
LL F(const board &b){
    static const LL w[16] = {
        65536 , 32768 , 16384 , 8192 ,
          512 ,  1024 ,  2048 , 4096 ,
          256 ,   128 ,    64 ,   32 ,
            2 ,     4 ,     8 ,   16
    };
    LL res = 0;
    int empty = 0;
    for(int i = 0 ; i < 16 ; ++i){
        if(b.data[i] == 0)
            empty += 1;
        else
            res += (1LL << b.data[i]) * w[i];
    }
    LL mono = 0;
    for(int r = 0 ; r < 4 ; ++r){
        int lst = -1;
        for(int c = 0 ; c < 4 ; ++c){
            int val = b.data[r * 4 + c];
            if(val){
                if(lst != -1){
                    if(r == 0 || r == 2)
                        if(lst < val)
                            mono += (1LL << val);
                    else
                        if(lst > val)
                            mono += (1LL << lst);
                }
                lst = val;
            }
        }
    }
    for(int c = 0 ; c < 4 ; ++c){
        int lst = -1;
        for(int r = 0 ; r < 4 ; ++r){
            int val = b.data[r * 4 + c];
            if(val){
                if(lst != -1 && lst < val)
                    mono += (1LL << val);
                lst = val;
            }
        }
    }
    return res - mono * 8 + empty * 10000000LL;
}
struct Node{
    int fa;
    char move;
};
struct BeamState{
    board b;
    int seq;
    LL score;
    int id;
};
struct temp{
    board b;
    int seq;
    LL score;
    int fa;
    char move;
};
vector<Node> tree;
bool cmp(const temp &a , const temp &b){
    return a.score > b.score;
}
string search(int seed , int exp , int K){
    tree.clear();
    tree.push_back({-1 , ' '});
    board initB;
    int cur_seq = seed;
    add(initB , cur_seq);
    add(initB , cur_seq);
    vector<BeamState> beam;
    beam.push_back({initB , cur_seq , F(initB) , 0});
    const char dirChar[] = {'L' , 'R' , 'U' , 'D'};
    unordered_set<pair<ULL , int> , hash_> visited;
    while(!beam.empty()){
        vector<temp> new_;
        visited.clear();
        for(const auto &st : beam){
            for(int d = 0 ; d < 4 ; ++d){
                board nb = st.b;
                bool moved = false;
                if(d == 0)
                    moved = moveL(nb);
                else if(d == 1)
                    moved = moveR(nb);
                else if(d == 2)
                    moved = moveU(nb);
                else if(d == 3)
                    moved = moveD(nb);
                if(!moved)
                    continue;
                int nseq = st.seq;
                add(nb , nseq);
                int mt = 0;
                for(int i = 0 ; i < 16 ; ++i)
                    if(nb.data[i] > mt)
                        mt = nb.data[i];
                if(mt >= exp){
                    string path = "";
                    path += dirChar[d];
                    int curr = st.id;
                    while(curr != 0){
                        path += tree[curr].move;
                        curr = tree[curr].fa;
                    }
                    reverse(path.begin() , path.end());
                    return path;
                }
                auto state_ = make_pair(nb.hash() , nseq);
                if(visited.count(state_))
                    continue;
                visited.insert(state_);
                LL sc = F(nb);
                new_.push_back({nb , nseq , sc , st.id , dirChar[d]});
            }
        }
        if(new_.empty()) break;
        sort(new_.begin() , new_.end() , cmp);
        if(new_.size() > (ULL)K)
            new_.resize(K);
        beam.clear();
        for(const auto &ts : new_){
            tree.push_back({ts.fa , ts.move});
            beam.push_back({ts.b , ts.seq , ts.score , (int)tree.size() - 1});
        }
    }
    return "";
}
int main(){
    tree.reserve(50000000);
    for(int seed = 1 ; seed <= 20 ; ++seed){
        int exp = (seed <= 2) ? 12 : (seed <= 5) ? 13 : (seed <= 10) ? 14 : 15;
        string moves = "";
        int K_values[] = {5 , 25 , 100 , 500};
        printf("Try for seed %d (target: 2^%d)\n" , seed , exp);
        for(int K : K_values){
            moves = search(seed , exp , K);
            if(!moves.empty()){
                printf("-> Success with K = %d, total moves = %d, \n" , K , (int)moves.size());
                break;
            }
            else
                printf("-> Failed with K = %d, retrying with larger width...\n" , K);
        }
        if(!moves.empty()){
            string filename = "2048" + to_string(seed) + ".out";
            ofstream fout(filename);
            fout << seed << "\n" << moves << "\n";
            fout.close();
        }
        else
            printf("-> ALL FAILED for seed %d\n" , seed);
    }
    return 0;
}

::::

本地测试结果:

可以看到由于估值函数较优,搜索次数还是比较少的,在学校 i5-7400、4G,甚至开个网页都可能内存耗尽的情况下,仍然只用了 54.28s 就能跑出结果。

反思

这是 k=500 的测试结果:

可以看到,由于 k 较大,搜索次数明显增多,导致时间增加;但是步数明显减少,因为 k 较大的情况下,搜索情况变多,可以找到更优解。

::::info[k=25,50,100,500 的测试结果]

::::

结语

所以说啊,有的时候感觉前路坎坷,不一定是因为不够优秀,只是一时得失罢了。一时的落后,或许只是通往 32768 的路径上,必不可少的蛰伏与让步。

厚积薄发,未来可期。祝你在每一场“搜索”里,都能找到属于自己的最优解。

AI 使用说明:作者的估值函数设计部分参考了 Gemini 的设计。