跳到正文

题解

[UVA10503] The dominoes solitaire 题解

Oracynx约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月23日
篇幅
约 5 分钟
获赞
2
题目
UVA10503

版本

  1. v1当前

[UVA10503] The dominoes solitaire 题解

题目大意

给你 mm 个两面都有数字的木块,定义一串合法的木块序列为两个木块间相对的两面的数字相同。

如 (1,2),(2,4),(4,4),(4,7)(1, 2), (2, 4), (4, 4), (4, 7) 为合法序列。

(1,2),(1,3),(3,4)(1, 2), (1, 3), (3, 4) 等则为不合法序列。

再指定两个木块作为第一个和最后一个(不可反转)。

问是否有方案使得从 mm 个木块中选出 nn 个经过任意的旋转重排后使得有 n+2n + 2 个木块的整个序列合法。

其中 m≤14m \le 14。

思路分析

看到 m≤14m \le 14,这道题需要暴力解决。

但是 m!≈1011m! \approx 10^{11},所以不能直接暴力。

一种可行的方式:

我们在每次选出一个木块后需要保证这个木块和上一个能够拼接在一起。

这样就可以了。

吗?

考虑下面数据。

代码
14
14
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
2 2
0

这样很多都能够拼上,但是由于只有 1313 个能够拼上,一共需要 1212 个。

所以每一个都在最后一位失败。

但是前面的 1313 个 (1,1)(1, 1) 相当于跑了一遍全排列。

13!≈6×10913! \approx 6 \times 10^9,超时。

所以当前位置的填入目标还要选一个在当前位置没有试过的填入。

暴力剪枝题目不好分析复杂度,可以看作实际搜索的方案数远远低于 m!m! 量级,故可通过此题。

代码实现

对于 dfs 函数,其中的 use 表示当前是否选过了 (a,b)(a, b)。

我们需要尝试找到一个合法的放置方案。

令这个木块上的数字为 (a,b)(a, b),上一个木块末尾为 prepre。

不难发现如果 b=preb = pre 则交换 aa 和 bb 不劣。

分类讨论。

  • a=pre,b=prea = pre, b = pre,交换,没有影响,不劣。
  • a≠pre,b≠prea \not = pre, b \not = pre,不交换,没有影响,不劣。
  • a=pre,b≠prea = pre, b \not = pre,不交换,没有影响,不劣。
  • a≠pre,b=prea \not = pre, b = pre,交换,优于之前的顺序。

如果交换后仍然不合法,则填不下去了。

C++
#include <cstdio>
#include <cstdlib>
#include <map>
#include <tuple>
#include <utility>
constexpr int MaxN = 2e1 + 5;
int n, m;
int end;
int a[MaxN];
int b[MaxN];
int pre[MaxN];
bool vis[MaxN];
bool dfs(int u)
{
    if (u > n)
    {
        return pre[n] == end;
    }
    std::map<std::tuple<int, int>, bool> use;
    for (int i = 1; i <= m; i++)
    {
        if (vis[i])
        {
            continue;
        }
        if (b[i] == pre[u - 1])
        {
            std::swap(a[i], b[i]);
        }
        if (use[{a[i], b[i]}])
        {
            continue;
        }
        use[{a[i], b[i]}] = true;
        if (a[i] == pre[u - 1])
        {
            pre[u] = b[i];
            vis[i] = true;
            if (dfs(u + 1))
            {
                return true;
            }
            vis[i] = false;
        }
    }
    return false;
}
void solve()
{
    scanf("%d", &n);
    if (n == 0)
    {
        exit(0);
    }
    scanf("%d", &m);
    scanf("%*d%d", &pre[0]);
    scanf("%d%*d", &end);
    for (int i = 1; i <= m; i++)
    {
        vis[i] = false;
        scanf("%d%d", &a[i], &b[i]);
    }
    printf("%s\n", dfs(1) ? "YES" : "NO");
}
int main()
{
    for (;;)
    {
        solve();
    }
    return 0;
}
原文