【无标题】AtCoder Beginner Contest 2248 Puzzle on Graph

 

Takahashi found a puzzle along some road.
It is composed of an undirected graph with nine vertices and MM edges, and eight pieces.

The nine vertices of the graph are called Vertex 11, Vertex 22, \ldots…, Vertex 99. For each i = 1, 2, \ldots, Mi=1,2,…,M, the ii-th edge connects Vertex u_iui​ and Vertex v_ivi​.
The eight pieces are called Piece 11, Piece 22, \ldots…, Piece 88. For each j = 1, 2, \ldots, 8j=1,2,…,8, Piece jj is on Vertex p_jpj​.
Here, it is guaranteed that all pieces are on distinct vertices. Note that there is exactly one empty vertex without a piece.

Takahashi can do the following operation on the puzzle any number of times (possibly zero).

Choose a piece on a vertex adjacent to the empty vertex, and move it to the empty vertex.

By repeating this operation, he aims to complete the puzzle. The puzzle is considered complete when the following holds.

  • For each j = 1, 2, \ldots, 8j=1,2,…,8, Piece jj is on Vertex jj.

Determine whether it is possible for Takahashi to complete the puzzle. If it is possible, find the minimum number of operations needed to do so.

首先用邻接表存入这些边,然后把系统给的数字加上尾部,就可以开始bfs了,在bfs时我们首先记录初始点的字典值为1,然后后面如果发现有一种状态没有设置字典值则加入队列,当状态为123456789时结束并输出,如果到队列没子弹了还没找出来的话就输出负一,

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,e[9999],h[9999],ne[9999],idx,a[9999],b[9999],c[88];
string s="";
int add(int x,int y)
{
    e[idx]=y;
    ne[idx]=h[x];
    h[x]=idx++;
    return 0;
}
int bfs()
{
    map<string,int>p;
    queue<string>q;
    q.push(s);
    p[s]=1;
    while(!q.empty()) {
        string t=q.front();
        q.pop();
        if(t=="123456789")return cout<<p[t]-1<<endl,0;
        for(int i=h[t[8]-'0'-0]; ~i; i=ne[i]) {
            string tt=t;
            int x=0;
            for(int j=0; j<9; j++)
                if(tt[j]=='0'+e[i])x=j;
            char ttt=tt[8];
            tt[8]=tt[x];
            tt[x]=ttt;
            if(p[tt]==0) {
                p[tt]=p[t]+1;
                q.push(tt);
            }
        }

    }
    if(q.empty())cout<<-1;
    return 0;
}
signed main()
{
    map<int,int>q;
    memset(h,-1,sizeof h);
    char x;
    cin>>n;
    for(int i=0; i<n; i++) {
        int x,y;
        cin>>x>>y;
        add(x,y);
        add(y,x);
    }
    for(int i=0; i<8; i++)cin>>x,s+=x,q[x-'0']++;
    for(int i=1; i<10; i++)if(q[i]==0)s+=char(i+'0');
    bfs();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GSYMG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值