搜索与剪枝

一、玛雅游戏(开心消消乐)

洛谷P1312

分析

1.搜索顺序:每一步依次枚举操作哪个格子,再枚举向哪个方向移动。
2.剪枝

(1)如果某种颜色只有1个或2个小方块,则直接回溯。
(2)枚举向左移动时,如果左边有方块,则直接回溯。
解释:若右边的方块向左移,可以表示为(x, y, -1);而左边的方块向右移,可以表示为(x-1, y, 1)。由字典序排序可知,从左往右移动的方案永远排在前面。
(3)错误的剪枝向右移动时,如果右侧的方块颜色和当前方块颜色相同,则剪枝。 由于题目中要求步数恰好是 n的方案,因此这个无意义的操作可能被用来填补操作步数,因此不能被剪掉。

代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

int n;
int g[5][7], bg[5][5][7];  //g数组存图,bg数组用来备份恢复现场
int cnt[11], bcnt[5][11];  //cnt数组存储每个颜色当前个数,bcnt数组用来备份
bool st[5][7];  //st数组用来判重

struct Move
{
    int x, y, d; //x表示横坐标,y表示纵坐标,d=-1时表示向左移,d=1时表示向右移
}path[5];

void move(int a, int b, int c)
{
    swap(g[a][b], g[c][b]); //把g[a][b] -> g[c][b]
    while (true)
    {
        bool flag = false;
        //处理悬空方格
        for (int x = 0; x < 5; x++)    //双指针枚举每一行和每一列
        {
            int z = 0;
            for (int y = 0; y < 7; y++)
                if (g[x][y])
                    g[x][z++] = g[x][y];
            while (z < 7) g[x][z++] = 0;
        }
        memset(st, false, sizeof st);
        //枚举每个格子是否应该被删掉
        for (int x = 0; x < 5; x ++ )
            for (int y = 0; y < 7; y ++ )
                if (g[x][y])
                {
                    int l = x, r = x;   //判断行
                    while (l - 1 >= 0 && g[l - 1][y] == g[x][y]) l--;
                    while (r + 1 < 5 && g[r + 1][y] == g[x][y]) r++;
                    if (r - l + 1 >= 3)   //应该被删掉
                    {
                        flag = true;
                        st[x][y] = true;
                    }
                    else
                    {
                        l = r = y;     //判断列
                        while (l - 1 >= 0 && g[x][l - 1] == g[x][y]) l--;
                        while (r + 1 < 7 && g[x][r + 1] == g[x][y]) r++;
                        if (r - l + 1 >= 3)
                        {
                            flag = true;
                            st[x][y] = true;
                        }
                    }
                }
        if (flag)
        {
            for (int x = 0; x < 5; x ++ )
                for (int y = 0; y < 7; y ++ )
                    if (st[x][y])
                    {
                        cnt[0] --;
                        cnt[g[x][y]] --;
                        g[x][y] = 0;
                    }
        }
        else break;
    }
}

bool dfs(int u)
{
    if (u == n) return !cnt[0];
    for (int i = 1; i <= 10; i++)   //枚举所有颜色
        if (cnt[i] == 1 || cnt[i] == 2) //剪枝一:如果某种颜色只有1个或2个小方块,则直接回溯
            return false;
    //备份
    memcpy(bg[u], g, sizeof g);
    memcpy(bcnt[u], cnt, sizeof cnt);
    //枚举所有操作
    for (int x = 0; x < 5; x ++ )
        for (int y = 0; y < 7; y ++ )
            if (g[x][y])
            {
                int nx = x + 1;   //向右移动
                if (nx < 5)
                {
                    path[u] = { x, y, 1 };
                    move(x, y, nx);
                    if (dfs(u + 1)) return true;
                    //恢复现场
                    memcpy(g, bg[u], sizeof g);
                    memcpy(cnt, bcnt[u], sizeof cnt);
                }
                nx = x - 1;     //向左移动
                if (nx >= 0 && !g[nx][y]) //剪枝二:枚举向左移动时,如果左边有方块,则直接回溯
                {
                    path[u] = { x, y, -1 };
                    move(x, y, nx);
                    if (dfs(u + 1)) return true;
                    memcpy(g, bg[u], sizeof g);
                    memcpy(cnt, bcnt[u], sizeof cnt);
                }
            }

    return false;
}

int main()
{
    scanf("%d",&n);
    for (int x = 0; x < 5; x ++)
    {
        int y = 0, t;
        while (scanf("%d",&t), t)
        {
            cnt[0] ++;  //cnt[0]表示所有方块个数
            cnt[t] ++;
            g[x][y ++] = t;
        }
    }
    if (dfs(0))
    {
        for(int i = 0; i < n; i++) printf("%d %d %d\n", path[i].x, path[i].y, path[i].d);
    }
    else puts("-1");

    return 0;
}

二、虫食算

洛谷P1092

分析

1.搜索顺序:依次枚举每个字母代表哪个数字。
(由于时间复杂度为26! * 26 ,必然超时,故需要剪枝+边枚举边判断)
2.剪枝:对每一列对应字母
(1)如果后面所有字母都是确定的,则可以直接判断每一位是否合法。
(2)如果后面有某些字母没有确定,满足(A+B+0)% N = C或者(A+B+1)% N = C则合法。
(3)最高位不能有进位。

代码

#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;
const int N = 30;
int n;   //n进制
char e[3][N];
int q[N], path[N];  //q[]记录从右到左的次序,, path[]记录方案
bool st[N];     //记录state

bool check()
{
    for (int i = n - 1, t = 0; i >= 0; i --)
    {
        int a = e[0][i] - 'A', b = e[1][i] - 'A', c = e[2][i] - 'A'; //a表示每一列上加数的字母,b表示被加数,c表示和
        if (path[a] != -1 && path[b] != -1 && path[c] != -1)   //如果当前字母都已经赋过值,判断是否有矛盾
        {
            a = path[a], b = path[b], c = path[c];
            if (t != -1)  //t表示进位
            {
                if ((a + b + t) % n != c) return false;
                if (!i && a + b + t >= n) return false; //最高位不能有进位
                t = (a + b + t) / n;
            }
            else
            {
                if ((a + b + 0) % n != c && (a + b + 1) % n != c) return false;
                if (!i && a + b >= n) return false;
            }
        }
        else t = -1;
    }

    return true;
}

bool dfs(int u)
{
    if (u == n) return true; //搜索完最后一个字母,由于题目保证一定有解,因此已经得到了一个方案,返回
    for (int i = 0; i < n; i ++) //否则枚举当前这一为应该选哪个数字
        if (!st[i])
        {
            st[i] = true;
            path[q[u]] = i;
            if (check() && dfs(u + 1)) return true;
            st[i] = false;
            path[q[u]] = -1;
        }

    return false;
}

int main()
{
    scanf("%d", &n);
    for (int i = 0; i < 3; i ++) scanf("%s", e[i]);
    for (int i = n - 1, k = 0; i >= 0; i --)
        for (int j = 0; j < 3; j ++)
        {
            int t = e[j][i] - 'A';  //把当前字母映射成从0到25的一个数字
            if (!st[t])            //如果数字之前没有出现过
            {
                st[t] = true;
                q[k ++] = t;
            }
        }
    memset(st, 0, sizeof st);
    memset(path, -1, sizeof path);
    dfs(0);
    for (int i = 0; i < n; i ++) printf("%d ", path[i]);

    return 0;
}

三、字串变换

洛谷P1032

分析

1.第一次做到双向BFS问题,我们用双端队列来解决。
BFS的扩展方式是:分别枚举在原字符串中使用替换规则的起点,和所使用的替换规则。
2.优化搜索方式:从两个队列空间较少的一方进行扩展。
3.双向BFS一般用在最小步数模型中。

代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <unordered_map>   //开哈希表判断字符串是否已经搜过
#include <queue>          

using namespace std;
const int N = 6;
int n; //规则数量
string a[N], b[N];

int extend(queue<string>& q, unordered_map<string, int>& da, unordered_map<string, int>& db, string a[], string b[])
{
    int d = da[q.front()];
    while(q.size() && da[q.front()]==d)
    {
        auto t = q.front();
        q.pop();

        for(int i = 0; i < n; i ++)
            for(int j = 0; j < t.size(); j ++)
                if(t.substr(j, a[i].size()) == a[i])
                {
                    string st = t.substr(0, j) + b[i] + t.substr(j + a[i].size()); //中间部分换成b
                    if (da.count(st)) continue;
                    if (db.count(st)) return da[t] + db[st] + 1;
                    da[st] = da[t] + 1;
                    q.push(st);
                }
    }
    return 11; 
}

int bfs(string A, string B)
{
    queue <string> qa, qb;   //双端队列
    unordered_map <string, int> da, db;  //记录距离
    qa.push(A), da[A] = 0; 
    qb.push(B), db[B] = 0;
    int step = 0;
    while (qa.size() && qb.size())
    {
        int t;
        if (qa.size() <= qb.size()) t = extend(qa, da, db, a, b); //扩展qa队列,把a变成b
        else t= extend(qb, db, da, b, a);
        if(t <= 10) return t;
        if(++step == 10) return -1;
    }
    return -1; //只要一个队列为空,则无解。例如,若起点为空,则说明从起点开始已经把所有情况搜完了还没有到终点,则无解。
}

int main()
{
    string A, B; //A为起点,B为终点
    cin >> A >> B;
    while(cin >> a[n] >> b[n]) n ++;
    int step = bfs(A, B);
    if(step == -1) puts("NO ANSWER!");
    else printf("%d\n", step);

    return 0;
}

四、单词接龙

洛谷P1019

分析

1.可以把子串拼接过程看成一棵树,以开头字母为根节点,所有能够拼接的子串为一层,因此树的深度最多为40层。

代码

#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int N = 21;
int n;
string word[N];
int g[N][N];  //初始化每个单词和另一个单词之间是否有边
int used[N];  //记录每个单词当前用了多少次
int ans;

void dfs(string dragon, int last)
{
    ans = max((int)dragon.size(), ans);
    used[last] ++;
    for (int i = 0; i < n; i ++)        //枚举下一单词可以填哪个
        if (g[last][i] && used[i] < 2)  //如果last后面可以接i这个单词
            dfs(dragon + word[i].substr(g[last][i]), i);
    used[last] --; //回溯
}

int main()
{
    cin >> n;
    for (int i = 0; i < n; i ++) cin >> word[i];
    char start;
    cin >> start;
    //初始化查看一个单词是否能接在另一单词后面
    for (int i = 0; i < n; i ++)
        for (int j = 0; j < n; j ++)
        {
            string a = word[i], b = word[j];    //a表示第一个单词,b表示第二个单词
            for (int k = 1; k < min(a.size(), b.size()); k ++)     //为使拼接后的单词长度最长,重合部分越短越好,从小到大枚举长度
                if (a.substr(a.size() - k, k) == b.substr(0, k))  //a的后缀==b的前缀
                {
                    g[i][j] = k;  //记录重合部分最小长度
                    break;
                }
        }
    for (int i = 0; i < n; i ++)  //爆搜
        if (word[i][0] == start)
            dfs(word[i], i);
    cout << ans << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值