Đề bài ở đây: http://vn.spoj.com/problems/NK05EOPR/
Code của em đây, nhưng chạy quá thời gian?
#include <bits/stdc++.h>
using namespace std;
const string ok="abcdefghijkl";
int main()
{
// Tim xem dinh x co the thay doi voi dinh y nao?
int a[12][12];
memset(a,0,sizeof(a));
int d[5]={0,1,3,6,12};
for(int i=0; i<=11; i++)
for(int j=0; j<=11; j++)
if(i!=j)
{
int x=abs(i-j);
int k=0;
for(int ii=1; ii<=3; ii++)
if(x==d[ii])
{
k=ii;
break;
}
if(k==0) continue;
if(int(i/d[k+1])==int(j/d[k+1]))
{
a[i][0]++;
a[i][a[i][0]]=j;
}
}
// Nhap du lieu
int T;
scanf("%d",&T);
while(T--)
{
string input="";
for(int i=0; i<12; i++)
{
int x;
scanf("%d",&x);
//chuyen day so thanh dang xau
input+=char(x+int('a'));
}
// Duyet theo chieu rong BFS
unordered_map <string,int> InQueue;
InQueue[input]=1;
queue<string> lq;
bool found=false;
for(lq.push(input); !lq.empty(); lq.pop())
{
string tmp=lq.front();
int zero=tmp.find("a");
for(int i=1; i<=a[zero][0]; i++)
{
string s=tmp;
swap(s[zero],s[a[zero][i]]);
if(s==ok)
{
printf("%d\n",InQueue[tmp]);
found=true;
break;
}
if(!InQueue[s])
{
lq.push(s);
InQueue[s]=InQueue[tmp]+1;
//printf("%s\n",s.c_str());
}
}
if(found) break;
}
//printf("%s\n",input.c_str());
}
return 0;
}
Chả nhẽ mấy nghìn thành viên của diễn đàn Dạy Nhau Học không giải nổi bài toán này??