跳到正文

个人记录

11.16状压

Meovow约 6 分钟
原文

这是 2025年11月23日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟

版本

  1. v2当前
  2. v1

P8687 [蓝桥杯 2019 省 A] 糖果

(30pts)

这道题我们考虑dfs暴力,cur表示选到了第几包,st表示选择的糖果状态,cnt表示已经选了的数量。

每包糖果可以选或不选,等到所有的都跑完了之后看是不是要选的都选了就可以了,去选择数量的最小值。

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
int mini = 1e9, n, m, k; 
int tmp[N];
void dfs(int cur, int st, int cnt)
{
    if (cur == n + 1)
    {
        if (st == (1 << m) - 1)
            mini = min(mini, cnt); 
        return ;
    }
    dfs(cur + 1, st | (tmp[cur]), cnt + 1); 
    dfs(cur + 1, st, cnt); 
}
int main()
{
    cin >> n >> m >> k;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= k; j++)
        {
            int x;
            cin >> x;
            tmp[i] |= (1 << (x - 1));
        }
    dfs(1, 0, 0);
    if (mini == 1e9)
    {
        cout << -1;
        return 0;
    }
    cout << mini;
    return 0;
}

当然了如果当前要买的数量比原先的答案要大了就肯定不会是这个答案了所以直接结束就可以了,能拿到 6060 分。

P10449 费解的开关

可以考虑dfs第一步改哪个,第二步改哪个,一共考虑 66 步。

但是时间复杂度会达到 25225 ^ 2,肯定会超时。我们发现,这么多状态里面肯定会有重复的。同时发现二维不好处理,那么我们可以二维转成一维,每次修改就相当于更改很多位。每次可以选择改或者不改这一位,那么时间复杂度为 O(225)O(2 ^ {25})。

我们可以考虑反向跑,那么从全是 11 开始跑,每跑一步记录这一步最少需要跑多少次,如果跑的次数达到了 66 次,就没必要继续了,存储每种可能的答案,跑完之后直接输出对应输入的答案。

为了二维转一维的方便,我们可以写一个函数来转下标,写一个函数来变换状态。

C++
#include<bits/stdc++.h>
using namespace std;
int dis[(1 << 25)];
bool vis[(1 << 25)];
int get_id(int x, int y)
{
    if (x < 1 || x > 5 || y < 1 || y > 5) return -1; 
    return (x - 1) * 5 + y - 1;
}
int work(int x, int y)
{
    int tmp = 0;
    int a = get_id(x, y);
    int b = get_id(x - 1, y);
    int c = get_id(x, y - 1);
    int d = get_id(x, y + 1);
    int e = get_id(x + 1, y);
    if (a != -1) tmp |= (1 << a);
    if (b != -1) tmp |= (1 << b);
    if (c != -1) tmp |= (1 << c);
    if (d != -1) tmp |= (1 << d);
    if (e != -1) tmp |= (1 << e);
    return tmp;
}
void bfs()
{
    queue<int> q;
    int x = (1 << 25) - 1;
    vis[x] = 1;
    dis[x] = 0;
    q.push(x);
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        if (dis[u] > 5) continue;
        for (int i = 1; i <= 5; i++)
            for (int j = 1; j <= 5; j++)
            {
                int v = u ^ work(5 - i + 1, 5 - j + 1);
                if (!vis[v])
                {
                    q.push(v);
                    dis[v] = dis[u] + 1;
                    vis[v] = 1;
                }
            }
    }
}
void solve()
{
    int tmp = 0;
    for (int i = 1; i <= 5; i++)
    {
        for (int j = 1; j <= 5; j++)
        {
            char c;
            cin >> c;
            int x = c - '0';
            tmp = (tmp << 1) | x;
        }
    }
    bfs();
    if (!vis[tmp])
    {
        cout << "-1\n";
        return ;
    }
    cout << dis[tmp] << "\n";
    return ;
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
    int T;
    cin >> T;
    while (T--)
        solve();
    return 0;
}