HDU1195的双向bfs

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
	char num[4];
	int step,hash;
	void get_hash()
    {
        hash=(num[0]-'0')*1000+(num[1]-'0')*100+(num[2]-'0')*10+(num[3]-'0');
    }
}f,temp;
int dp[2][10000];
void bfs()
{
	queue<node>q[2];
	int nowq=0,nowstep=0;
	q[0].push(f);
	q[1].push(temp);
	dp[0][f.hash]=0;
	dp[1][temp.hash]=0;
	while(!q[0].empty()||!q[1].empty())
	{
		f=q[nowq].front();
		if(f.step>nowstep)
		{
			nowq=!nowq;
			nowstep++;
		}
		f=q[nowq].front();q[nowq].pop();
		if(dp[!nowq][f.hash]!=-1)
		{
			printf("%d\n",f.step+dp[!nowq][f.hash]);
			return;
		}
		int i,j;
		for(i=0;i<4;i++)
		{
			for(j=0;j<3;j++)
			{
				temp=f;
				temp.step++;
				if(j==0)//第i位+
				{
					temp.num[i]++;
                    if(temp.num[i]>'9')temp.num[i]='1';
                    temp.get_hash();
				}
				else if(j==1)//第i位-
				{
					temp.num[i]--;
                    if(temp.num[i]<'1')temp.num[i]='9';
                    temp.get_hash();
				}
				else//交换第i位和它右边一位
				{
					if(i==3)continue;
					swap(temp.num[i],temp.num[i+1]);
                    temp.get_hash();
				}
				if(dp[nowq][temp.hash]==-1)
				{
					dp[nowq][temp.hash]=temp.step;
					q[nowq].push(temp);
				}
			}
		}
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		memset(dp,-1,sizeof dp);
		scanf("%s%s",f.num,temp.num);
		f.get_hash();
		f.step=0;
		temp.get_hash();
		temp.step=0;
		bfs();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值