hdu 1194

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <cstring>

using namespace std;

int flag[10000];


inline void swap(char &a,char &b)
{
	int temp = a;
	a = b; 
	b = temp;
	return ;
}
struct node
{
	char s[5];
	node(){s[4]='\0';}
	node(char *ss)
	{
		for(int i=0;i<5;i++)
			s[i]=ss[i];
		return;
	}
	int getnumber()
	{
		return (s[0]-'0')*1000+(s[1]-'0')*100+(s[2]-'0')*10+s[3]-'0';
	}
	node handle_minus(int i)
	{  
		node str(s);
		int temp = str.s[i]-'0';
		temp --;str.s[i]=temp+'0';
		if(temp==0) str.s[i]='9';
		return str;
	}
	node handle_add(int i)
	{
		node str(s);
		int temp = str.s[i]-'0';
		temp++;
		if(temp==10)temp = 1;
		str.s[i]=temp+'0';
		return str;
	}
	node exchange(int i)
	{   
		node str(s);
		swap(str.s[i],str.s[i+1]);
		return str;
	}
};
queue<node> G;

int solve(char *n,char* m)
{
	memset(flag,-1,sizeof(flag));
	while(!G.empty()) G.pop();

	node en(n);
	node aim(m);int obj = aim.getnumber();
	G.push(en);flag[en.getnumber()]=0;
	if(strcmp(n,m)==0) return 0;

	while(!G.empty())
	{
		node e = G.front();G.pop();
		int num = e.getnumber();

		node temp;int nums;
		for(int i=0;i<4;i++)
		{
			temp = e.handle_minus(i);nums=temp.getnumber();
			if(nums==obj) {return flag[num]+1;}
			if(flag[nums]==-1) {flag[nums]=flag[num]+1;G.push(temp);}

			temp = e.handle_add(i);nums = temp.getnumber();
			if(nums==obj) {return flag[num]+1;}
			if(flag[nums]==-1) {flag[nums]=flag[num]+1;G.push(temp);}
			}
			for(int i=0;i<3;i++)
			{
			temp = e.exchange(i);nums = temp.getnumber();
			if(nums==obj) {return flag[num]+1;}
			if(flag[nums]==-1) 
			{flag[nums]=flag[num]+1;G.push(temp);}	
		}
	}
	return 0;
}
void init()
{
	int test;
	scanf("%d",&test);
	for(int i=0;i<test;i++)
	{
		char n[5],m[5];
		scanf("%s%s",&n,&m);
		printf("%d\n",solve(n,m));
	}
	return ;
}
int main()
{  
	init();
	return 0;
}

你可能感兴趣的:(hdu 1194)