Cod sursa(job #73374)

Utilizator gigi_becaliGigi Becali gigi_becali Data 18 iulie 2007 10:20:08
Problema Cutii Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.54 kb
/*
ID: blaster2
TASK: msquare
LANG: C++
*/
using namespace std;
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#define maxn 103071
#define pb push_back
struct nod { string pred; string actual;char type; int d; };

vector<nod>H[maxn];

int x[8];
string sink,t;
inline int hash(string p)
{
	int h=0;
	for(int i=0;i<p.size();++i)
		h*=10, h+=p[i]-'0';
	h%=maxn;
	return h;
}

int find(string p)
{
	int h=hash(p);
	vector<nod>::iterator it;
	for(it=H[h].begin();it!=H[h].end();++it)
		if(it->actual==p) return 1;
	return 0;
}

void bfs()
{
	int i, j;
	queue<string>Q;
	Q.push(t);
	string p, q;
	
	
	while(!Q.empty())
	{
		
		p=Q.front();
		vector<nod>::iterator it;
		nod r;
		int h=hash(p);
		for(it=H[h].begin();it!=H[h].end();++it)
			if(it->actual==p){r=*it; break;} 
		q=p;
		Q.pop();
		
		if(p==sink) break;
		reverse(p.begin(), p.end());
		
		if(!find(p))
		{
			nod t;
			t.d=r.d+1;
			t.type='A';
			t.pred=q;
			t.actual=p;
			
			H[hash(p)].pb(t);
			Q.push(p);
		}
		
		{
			p=q;
			p[0]=q[3]; p[1]=q[0]; p[2]=q[1]; p[3]=q[2]; p[4]=q[5]; p[5]=q[6]; p[6]=q[7]; p[7]=q[4];
			if(!find(p))
			{
				nod t;
				t.d=r.d+1;
				t.type='B';
				t.pred=q;
				t.actual=p;
				H[hash(p)].pb(t);
				Q.push(p);
			}
		}
			
		{
			p=q;
			p[0]=q[0]; p[1]=q[6]; p[2]=q[1]; p[3]=q[3]; p[4]=q[4]; p[5]=q[2]; p[6]=q[5]; p[7]=q[7];
			if(!find(p))
			{
				nod t;
				t.d=r.d+1;
				t.type='C';
				t.pred=q;
				t.actual=p;
				H[hash(p)].pb(t);
				Q.push(p);
			}
		}
		
	}
	
}

void afis(string p)
{
	nod r;
	vector<nod>::iterator it;
	int h=hash(p);
		for(it=H[h].begin();it!=H[h].end();++it)
			if(it->actual==p){r=*it; break;} 
			
	if(find(r.pred))
	{
		afis(r.pred);
		printf("%c", r.type);
	}
}


int main()
{
//	freopen("msquare.in","r",stdin);
	//freopen("msquare.out","w",stdout);
	double start=clock();
	int i;
	//for(i=0;i<8;++i) scanf("%d ",x+i);
	x[0]=4; x[1]=3; x[2]= 1; x[3]=2;x[4]=5;x[5]=6;x[6]= 7;x[7]= 8;
	for(i=0;i<8;++i) sink+=(char)x[i]+'0';
	
	for(i=1;i<=8;++i) t+=(char)i+'0';
	nod r;
	r.type=0;
	r.actual=t;
	r.d=0;
	int h=hash(t);
	H[h].pb(r);
	
	bfs();
	nod s;
	vector<nod>::iterator it;
	 h=hash(sink);
		for(it=H[h].begin();it!=H[h].end();++it)
			if(it->actual==sink){s=*it; break;}
	printf("%d\n", 	s.d);		
	afis(sink);
	printf("\n");
	fprintf(stderr, "%lf\n", (clock()-start)/(double)CLOCKS_PER_SEC);
	return 0;
}