2021年ICPC(沈阳)Luggage Lock (BFS)

Posted jpphy0

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2021年ICPC(沈阳)Luggage Lock (BFS)相关的知识,希望对你有一定的参考价值。

目录

问题

分析

  • 类比:平面上有两点a和b,若a和b同步移动,则两点间的距离不变;特殊地,当a移动到原点(0,0),a、b间的距离就是b到原点的距离。
  • 密码锁的两个状态,作同步转动,不会改变两个状态间的距离(状态距离:从一个状态转动到另一个状态的步骤)
  • 基于以上性质,可以将两个状态同步转动,使得初始转态变成0000;因此,每一个查询都可以看作是从0000出发的
  • 从0000出发,到达其它状态的最小步骤 —— 迷宫问题,一次BFS即可解决,复杂度 O ( 20 ⋅ n ) O(20\\cdot n) O(20n)

代码

#include<bits/stdc++.h>
using namespace std;
const int mxn = 10010;
queue<int> q;
int n, h[mxn], ans[mxn], tot = 0, vis[mxn], d[4] = 1, 10, 100, 1000;
struct Edgeint to, nxt; edge[mxn<<5];
void add(int u, int v)
    edge[++tot].nxt = h[u], h[u] = tot, edge[tot].to = v;

void nxt(int s) // 仅需考虑+1的旋转
    int c[4];
    for(int j = s, i = 0; i < 4; ++i) c[i] = j%10, j /= 10;
    for(int len = 1; len <= 4; ++len)
        for(int ns, j, i = 0; i <= 4-len; ++i)
            for(ns = s, j = i; j < i+len; ++j)
                ns -= c[j]*d[j], ns += (c[j] == 9?0:c[j]+1)*d[j];
            add(s, ns), add(ns, s);
            if(vis[ns]) continue;
            vis[ns] = 1, q.push(ns);
        
    

void init()// 前向星构图
    memset(h, -1, sizeof h);
    memset(vis, 0, sizeof vis);
    q.push(0), vis[0] = 1;
    while(!q.empty()) nxt(q.front()), q.pop();

int trans(int s, int t)// 状态变换,返回变换后的末状态
    int c[4], b[4];
    for(int j = s, i = 0; i < 4; ++i) c[i] = j%10, j /= 10;
    for(int j = t, i = 0; i < 4; ++i) b[i] = j%10, j /= 10;
    for(int i = 0; i < 4; ++i) b[i] = (b[i]+10-c[i])%10;
    return b[0]+b[1]*10+b[2]*100+b[3]*1000;

int main()
    int s, t;
    init();
    memset(ans, 0x3f, sizeof ans);
    ans[0] = 0, q.push(0);
    while(!q.empty())        
        s = q.front(), q.pop();
        for(int j = h[s]; ~j; j = edge[j].nxt)
            t = edge[j].to;
            if(ans[t] > ans[s]+1) q.push(t), ans[t] = ans[s]+1;
        
    
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i)
        scanf("%d%d", &s, &t);
        printf("%d\\n", ans[trans(s, t)]);
    
    return 0;

以上是关于2021年ICPC(沈阳)Luggage Lock (BFS)的主要内容,如果未能解决你的问题,请参考以下文章

2021年ICPC(沈阳)Luggage Lock (BFS)

2021年ICPC(沈阳)Luggage Lock (BFS)

2021 ICPC沈阳 J.Luggage Lock(bfs,模拟)

2021 ICPC沈阳 J.Luggage Lock(bfs,模拟)

2021年ICPC(沈阳)Bitwise Exclusive-OR Sequence(图论)

2021年ICPC(沈阳)Bitwise Exclusive-OR Sequence(图论)