-4

Could somebody explain the solution to this problem in cpp and how it works Can this be made more efficient using STL?

http://www.codechef.com/problems/H1

It would very helpful if you could explain this particular logic along with its time complexity.


#include <cstdio>
using namespace std;
 
int board[9],q[178000]={123456789},powers[9]={100000000,10000000,1000000,100000,10000,1000,100,10,1};
int posn,fromposn,front=-1,back=1;
char found[98765435]={0};
bool prime[18]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1};
 
void moveit(int p1,int p2){
  int diff=board[p2]-board[p1];
  posn=fromposn+diff*powers[p1]-diff*powers[p2];
  int posndiv10=posn/10;
  if(!found[posndiv10]){
    found[posndiv10]=found[fromposn/10]+1;
    q[back++]=posn;
  }
}
 
int main(){
  int t,i,d;
 
#ifndef ONLINE_JUDGE
  freopen("in.txt","r",stdin);
#endif
  found[12345678]=1;
  while(++front<back){
    for(posn=fromposn=q[front],i=8;i>=0;i--){
      board[i]=posn%10;
      posn/=10;
    }
    if(prime[board[0]+board[1]]) moveit(0,1);
    if(prime[board[0]+board[3]]) moveit(0,3);
    if(prime[board[1]+board[2]]) moveit(1,2);
    if(prime[board[1]+board[4]]) moveit(1,4);
    if(prime[board[2]+board[5]]) moveit(2,5);
    if(prime[board[3]+board[4]]) moveit(3,4);
    if(prime[board[3]+board[6]]) moveit(3,6);
    if(prime[board[4]+board[5]]) moveit(4,5);
    if(prime[board[4]+board[7]]) moveit(4,7);
    if(prime[board[5]+board[8]]) moveit(5,8);
    if(prime[board[6]+board[7]]) moveit(6,7);
    if(prime[board[7]+board[8]]) moveit(7,8);
  }
  scanf("%d",&t);
  while(t--){
    for(posn=i=0;i<8;i++){
      scanf("%d",&d);
      posn=posn*10+d;
    }
    scanf("%d",&d);
    if(found[posn]) printf("%d\n",found[posn]-1);
    else puts("-1");
  }
  return 0;
}   

ruhuse
  • 5
  • 3
  • Please focus your qustion on a small part of that code which is particularily unclear. Consider to focus on "Can this be more efficient by using STL?", mentioning a specific construct provided by STL and a specific part of the code where you think it might help. – Yunnosch Jul 14 '20 at 06:38

1 Answers1

0

It first builds a table of all the solvable boards, represented as numbers, that says how many steps from the solution that board is.

Then it solves each test case by looking it up in that table.

The time complexity per test case is constant.

I doubt that there is anything in the standard library that could make it more efficient.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82