Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com

And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE

Sunday, January 11, 2015

NAKANJ-Minimum Knight moves !!!

Minimum Knight moves !!!

Given below code is for nakanj spoj or minimum knight moves spoj.


Question is same as costly chess(CCHESS) problem of spoj.




#include <bits/stdc++.h>
using namespace std;
#define MP make_pair
int dist[100][100];
map<int , pair<int , int > > mp;
map<pair<int , int > , int > m;
void fill_distance(int v){
    int path[8][2];
    int x = mp[v].first , y = mp[v].second;
    path[0][0] = x+2 , path[0][1] = y+1;
    path[1][0] = x+2 , path[1][1] = y-1;
    path[2][0] = x-2 , path[2][1] = y+1;
    path[3][0] = x-2 , path[3][1] = y-1;
    path[4][0] = x+1 , path[4][1] = y+2;
    path[5][0] = x+1 , path[5][1] = y-2;
    path[6][0] = x-1 , path[6][1] = y+2;
    path[7][0] = x-1 , path[7][1] = y-2;

    for(int i = 0 ; i < 8 ; i ++)
    {
        if(path[i][0] >= 0 && path[i][0] < 8 && path[i][1] >= 0 && path[i][1] < 8){
            dist[v][m[MP(path[i][0] , path[i][1])]] = 1;
        }
    }
}
void pre(){
    int k = 0;
    for(int i = 0 ; i < 64 ; i++)
        for(int j = 0 ; j < 64 ; j++){
            dist[i][j] = 9999999;
            dist[j][j] = 0;
        }
    for(int i = 0 ; i<64 ; i++){
        fill_distance( i);
    }
    for(int k = 0 ; k < 64 ; k++)
        for(int i = 0 ; i < 64 ; i++)
            for(int j = 0 ; j < 64 ; j++)
                    dist[i][j] = min(dist[i][j] , dist[i][k] + dist[k][j]);
}
int main()
{
    int k = 0;
    for(int i = 0 ; i < 8 ; i++)
        for(int j = 0 ; j < 8 ; j++){
            mp[k] = MP(i , j);
            m[MP(i , j)] = k;
            k++;
        }
    pre();
    int t;
    scanf("%d ",&t);
    while(t--){
        char inp[10];
        gets(inp);
        int x, y , u ,v;
        x = inp[0] - 97;
        y = inp[1] - 49;
        u = inp[3] - 97;
        v = inp[4] - 49;
        int source = m[MP(x,y)], dest = m[MP(u,v)];
        printf("%d\n",dist[source][dest]) ;
    }
    return 0;
}

No comments:

Post a Comment

Your comment is valuable to us