【A*】hdu 1195 Open the Lock

http://acm.hdu.edu.cn/showproblem.php?pid=1195

题意:每一位上的数字可以加1或减1;相邻的数可以交换(第1个和第4个不相邻),变换得到下面的密码。

分析:两个评价函数:f=g+h(g:每一位上与答案不相同数字的个数;h:步数)


#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

char strx[4],stry[4];
int vis[10005];  //判重
struct NUM{
	char cs[4];
	int pri,step;
	evaluate(){
		pri=0;
		for(int i=0;i<4;i++){
			if(cs[i]!=stry[i]) pri++;
		}
	}
};
bool operator < (struct NUM A,struct NUM B){
	return A.pri>B.pri;
}

inline int convert(char *str)
{
	int temp=0;
	for(int i=0;i<4;i++){
		temp=temp*10+(str[i]-'0');
	}
	return temp;
}

void BFS()
{
	priority_queue<NUM>pq1;
	NUM t,pt;
	int i,temp;
	char c1,c2;
	
	memset(vis,0,sizeof(vis));
	strcpy(t.cs,strx);
	t.step=0;
	temp=convert(t.cs);
	vis[temp]=1;
	pq1.push(t);
	
	while(!pq1.empty()){
		t=pq1.top();pq1.pop();
		t.evaluate();
		if(t.pri==0){
			printf("%d\n",t.step);break;
		}
		pt.step=t.step+1;
		for(i=0;i<4;i++){
			strcpy(pt.cs,t.cs);
			c1=c2=pt.cs[i]-'0';
			c1++;
			if(c1>9) c1=1;
			pt.cs[i]=c1+'0';
			temp=convert(pt.cs);
			if(!vis[temp]){
				vis[temp]=1;
				pt.evaluate();pt.pri+=pt.step;
				pq1.push(pt);
			}
			
			strcpy(pt.cs,t.cs);
			c2--;
			if(c2<1) c2=9;
			pt.cs[i]=c2+'0';
			temp=convert(pt.cs);
			if(!vis[temp]){
				vis[temp]=1;
				pt.evaluate();pt.pri+=pt.step;
				pq1.push(pt);
			}
		}
		for(i=0;i<3;i++){
			strcpy(pt.cs,t.cs);
			c1=pt.cs[i];pt.cs[i]=pt.cs[i+1];pt.cs[i+1]=c1;  //swap
			temp=convert(pt.cs);
			if(!vis[temp]){
				vis[temp]=1;
				pt.evaluate();pt.pri+=pt.step;
				pq1.push(pt);
			}
		}
	}
}

int main()
{
	int T;
	scanf("%d",&T);
	while(T--){
		scanf("%s%s",strx,stry);
		BFS();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值