King Richard's Knights


Problem Statement :


King Richard is leading a troop of  knights into battle! Being very organized, he labels his knights  and arranges them in an  square formation, demonstrated below:

Before the battle begins, he wants to test how well his knights follow instructions. He issues  drill commands, where each command follows the format ai bi di and is executed like so:

All knights in the square having the top-left corner at location  and the bottom-right corner at location  rotate  in the clockwise direction. Recall that some location  denotes the cell located at the intersection of row  and column . For example:


You must follow the commands sequentially. The square for each command is completely contained within the square for the previous command. Assume all knights follow the commands perfectly.

After performing all  drill commands, it's time for battle! King Richard chooses knights  for his first wave of attack; however, because the knights were reordered by the drill commands, he's not sure where his chosen knights are!

As his second-in-command, you must find the locations of the knights. For each knight , , print the knight's row and column locations as two space-separated values on a new line.

Input Format

This is broken down into three parts:

The first line contains a single integer, .
The second line contains a single integer, .
Each line  of the  subsequent lines describes a command in the form of three space-separated integers corresponding to , , and , respectively.
The next line contains a single integer, .
Each line  of the  subsequent lines describes a knight the King wants to find in the form of a single integer



Output Format

Print  lines of output, where each line  contains two space-separated integers describing the respective row and column values where knight  is located.



Solution :



title-img


                            Solution in C :

In   C  :







#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>

int main()
{
    int64_t N, S, L;
    int64_t * command, *initialArea, *searchArea;

    scanf ( "%lld", &N );
    scanf ( "%lld", &S );
    command = ( int64_t * ) malloc ( 3 * S * sizeof ( int64_t ) );
    initialArea = ( int64_t * ) malloc ( 3 * S * sizeof ( int64_t ) );
    searchArea = ( int64_t * ) malloc ( 4 * S * sizeof ( int64_t ) );

    for ( int64_t i = 0; i < S; i++ )
    {
        scanf ( "%lld%lld%lld", command + i * 3, command + i * 3 + 1, command + i * 3 + 2 );
        command[3 * i + 0]--;
        command[3 * i + 1]--;
    }

    initialArea[0] = command[0];
    initialArea[1] = command[1];
    initialArea[2] = command[2];
    searchArea[4 * 0 + 0] = initialArea[3 * 0 + 0];
    searchArea[4 * 0 + 1] = initialArea[3 * 0 + 0] + initialArea[3 * 0 + 2];
    searchArea[4 * 0 + 2] = initialArea[3 * 0 + 1];
    searchArea[4 * 0 + 3] = initialArea[3 * 0 + 1] + initialArea[3 * 0 + 2];

    for ( int64_t i = 1; i < S; i++ )
    {
        int64_t di = command[3 * i + 0] - command[3 * ( i - 1 ) + 0];
        int64_t dj = command[3 * i + 1] - command[3 * ( i - 1 ) + 1];

        initialArea[3 * i + 2] = command[3 * i + 2];

        switch ( i % 4 )
        {
            case 0:
                initialArea[3 * i + 0] = initialArea[3 * ( i - 1 ) + 0] + di;
                initialArea[3 * i + 1] = initialArea[3 * ( i - 1 ) + 1] + dj;
                break;

            case 1:
                initialArea[3 * i + 0] = initialArea[3 * ( i - 1 ) + 0] - dj + initialArea[3 * ( i - 1 ) + 2] - initialArea[3 * i + 2];
                initialArea[3 * i + 1] = initialArea[3 * ( i - 1 ) + 1] + di;
                break;

            case 2:
                initialArea[3 * i + 0] = initialArea[3 * ( i - 1 ) + 0] - di + initialArea[3 * ( i - 1 ) + 2] - initialArea[3 * i + 2];
                initialArea[3 * i + 1] = initialArea[3 * ( i - 1 ) + 1] - dj + initialArea[3 * ( i - 1 ) + 2] - initialArea[3 * i + 2];
                break;

            case 3:
                initialArea[3 * i + 0] = initialArea[3 * ( i - 1 ) + 0] + dj;
                initialArea[3 * i + 1] = initialArea[3 * ( i - 1 ) + 1] - di + initialArea[3 * ( i - 1 ) + 2] - initialArea[3 * i + 2];
                break;
        }

        searchArea[4 * i + 0] = initialArea[3 * i + 0];
        searchArea[4 * i + 1] = initialArea[3 * i + 0] + initialArea[3 * i + 2];
        searchArea[4 * i + 2] = initialArea[3 * i + 1];
        searchArea[4 * i + 3] = initialArea[3 * i + 1] + initialArea[3 * i + 2];

    }

    // for ( int64_t i = 0; i < S; i++ )
    // {
    // printf ( "(%d, %d, %d) (%d, %d, %d)\n", command[3 * i + 0], command[3 * i + 1], command[3 * i + 2], initialArea[3 * i + 0], initialArea[3 * i + 1], initialArea[3 * i + 2]);
    // }

    scanf ( "%lld", &L );

    while ( L-- > 0 )
    {
        int64_t w;
        scanf ( "%lld", &w );

        int64_t i = w / N, j = w % N;

        int64_t max = S - 1, min = -1, last = max / 2;

        while ( max > min )
        {
            if ( i >= searchArea[4 * last + 0] &&
                    i <= searchArea[4 * last + 1] &&
                    j >= searchArea[4 * last + 2] &&
                    j <= searchArea[4 * last + 3] )
            {
                min = last;
                int64_t temp = min + max;

                if ( temp % 2 == 1 )
                {
                    last = temp / 2 + 1;
                }
                else
                {
                    last = temp / 2;
                }
            }
            else
            {
                max = last - 1;
                last = ( min + max ) / 2;
            }
        }

        // printf("last = %lld\n", last);

        int64_t di = i - initialArea[3 * last + 0];
        int64_t dj = j - initialArea[3 * last + 1];

        if ( last >= 0 )
        {

            switch ( ( last + 1 ) % 4 )
            {
                case 0:
                    i = di + command[3 * last + 0];
                    j = dj + command[3 * last + 1];
                    break;

                case 1:
                    i = dj + command[3 * last + 0];
                    j = command[3 * last + 1] + command[3 * last + 2] - di;
                    break;

                case 2:
                    i = command[3 * last + 0] + command[3 * last + 2] - di;
                    j = command[3 * last + 1] + command[3 * last + 2] - dj;
                    break;

                case 3:
                    i = command[3 * last + 0] + command[3 * last + 2] - dj;
                    j = di + command[3 * last + 1];
                    break;
            }
        }

        printf ( "%lld %lld\n", i + 1, j + 1 );
    }

    return 0;
}
                        


                        Solution in C++ :

In  C++  :







#include <bits/stdc++.h>
using namespace std;

int S,N,L;

typedef complex<int> pt;

struct state {
	pt orig;
	pt now;
	int d,idx;

	pt get_at(int x,int y) {
		x-=real(now);
		y-=imag(now);
		int rots=idx%4;
		swap(x,y);
		for(;rots--;) {
			int tmp=x;
			x=y;
			y=d-tmp;
		}
		swap(x,y);
		return pt(real(orig)+x,imag(orig)+y);
	}
	bool has(int x,int y) {
		return x>=real(orig) && y>=imag(orig) && x<=real(orig)+d && y<=imag(orig)+d;
	}

	pt rlook(int x,int y) {
		swap(orig,now);
		idx = 4-(idx%4);
		pt ans=get_at(x,y);
		idx=4-(idx%4);
		swap(orig,now);
		return ans;
	}
};
vector<state> vs;

int main() {
	cin>>N>>S;
	vs.push_back({pt(1,1),pt(1,1),N-1,0});
	for(int i=1;i<=S;i++) {
		int a,b,d; cin>>a>>b>>d;
		pt ul=vs.back().get_at(a,b);
		pt dr=vs.back().get_at(a+d,b+d);
		pt neworig={min(real(ul),real(dr)), min(imag(ul),imag(dr))};
		pt newnow={a,b};
		vs.push_back({neworig,newnow,d,i});
	}

	for(auto &st : vs) {
//		cout<<st.orig<<" "<<st.now<<" "<<st.d<<" "<<st.idx<<endl;
	}

cin>>L;
for(;L--;) {
long long w; cin>>w;
int x=w/N+1;
int y=w%N+1;
int lb=0,rb=S;
for(;lb<rb;) {
int mb=(lb+rb+1)/2;
if(vs[mb].has(x,y)) lb=mb;
else rb=mb-1;
}
pt p=vs[lb].rlook(x,y);
cout<<real(p)<<" "<<imag(p)<<endl;
}


}
                    


                        Solution in Java :

In  Java  :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int s = sc.nextInt();
        long[] a = new long[s+1];
        long[] b = new long[s+1];
        long[] d = new long[s+1];
        long[] tln = new long[s+1];
        a[0] = 1;
        b[0] = 1;
        d[0] = n-1;
        for (int i = 1; i <= s; i++) {
            a[i] = sc.nextInt();
            b[i] = sc.nextInt();
            d[i] = sc.nextInt();
            if (i%4==1) {
                tln[i] = tln[i-1]+(a[i]-a[i-1])*n+(b[i]-b[i-1]);
            } else if (i%4==2) {
                tln[i] = tln[i-1]+((b[i-1]+d[i-1])-(b[i]+d[i]))*n+(a[i]-a[i-1]);
            } else if (i%4==3) {
                tln[i] = tln[i-1]+((a[i-1]+d[i-1])-(a[i]+d[i]))*n+((b[i-1]+d[i-1])-(b[i]+d[i]));
            } else if (i%4==0) {
                tln[i] = tln[i-1]+(b[i]-b[i-1])*n+((a[i-1]+d[i-1])-(a[i]+d[i]));
            }
        }
        
        int l = sc.nextInt();
        long[] w = new long[l];
        for (int i = 0; i < l; i++) {
            w[i] = sc.nextLong();
            int low = 0;
            int high = s;
            while (low != high) {
                int mid = (low+high+1)/2;
                if (w[i] >= tln[mid] && w[i] < tln[mid]+(d[mid]+1)*n && w[i]%n >= tln[mid]%n && w[i]%n <= (tln[mid]%n)+d[mid])
                    low = mid;
                else
                    high = mid-1;
            }
            long off1 = (w[i]-tln[low])/n;
            long off2 = (w[i]-tln[low])%n;
            if (low%4==0) {
                System.out.println((a[low]+off1)+" "+(b[low]+off2));
            } else if (low%4==1) {
                System.out.println((a[low]+off2)+" "+(b[low]+d[low]-off1));
            } else if (low%4==2) {
                System.out.println((a[low]+d[low]-off1)+" "+(b[low]+d[low]-off2));
            } else if (low%4==3) {
                System.out.println((a[low]+d[low]-off2)+" "+(b[low]+off1));
            }
        }
    }
}
                    


                        Solution in Python : 
                            
In   Python3 :



def mat_fac(f):
    a, b, d = drill[dn]
    if f == 1:
        return(((a-b, a+b+d), ((0, 1), (-1,0))))
    elif f == 2:
        return(((2*a+d, 2*b+d), ((-1, 0), (0, -1))))
    elif f == 3:
        return(((a+b+d, b-a), ((0, -1), (1, 0))))
        
def mat_mult(fac, pf):
    c2, d2 = fac[0]
    c1, d1 = pf[0]
    k1, k2 = fac[1]
    m1, m2 = pf[1]
    cnext, dnext = c2+k1[0]*c1+k1[1]*d1, d2+k2[0]*c1+k2[1]*d1
    knext1 = (k1[0]*m1[0]+k1[1]*m2[0], k1[0]*m1[1]+k1[1]*m2[1])
    knext2 = (k2[0]*m1[0]+k2[1]*m2[0], k2[0]*m1[1]+k2[1]*m2[1])
    return(((cnext, dnext), (knext1, knext2)))

def revnew(drn, row, col):
    c, d = drill[drn][3][0]
    k1, k2 = drill[drn][3][1]
    nrow = c + k1[0]*row + k1[1]*col
    ncol = d + k2[0]*row + k2[1]*col
    return((nrow, ncol))

def contained(x, row, col):
    a, b, d, f = drill[x]
    if row < a or row > a+d: return(0)
    elif col < b or col > b+d: return(0)
    else: return(1)
    
def bin_s(row, col):
    lower, upper = 0, len(drill)-1
    if not contained(lower, row, col):
        return((row, col))
    nrow, ncol = revnew(upper, row, col)
    if contained(upper, nrow, ncol):
        return((nrow, ncol))
    while lower < upper:
        x = lower+(upper-lower)//2
        nrow, ncol = revnew(x, row, col)
        if contained(x, nrow, ncol):
            if not contained(x+1, nrow, ncol):
                return((nrow, ncol))
            else:
                lower = x + 1; continue
        else:
            upper = x
    nrow, ncol = revnew(lower, row, col)
    return((nrow, ncol))
        
### Read Data
N = int(input())
S = int(input())
drill = [[int(t) for t in input().split()] for i in range(S)]
L = int(input())
trusty_k = [int(input()) for i in range(L)]

# Process drill matrix to get factors
dn = 0
while dn < len(drill):
    if drill[dn][2] == 0:
        del(drill[dn])
        continue
    elif dn+3 < len(drill) and drill[dn] == drill[dn+3]:
        del(drill[dn:dn+4])
        continue
    elif dn+2 < len(drill) and drill[dn] == drill[dn+2]:
        factor = mat_fac(3)
        del(drill[dn:dn+2])
    elif dn+1 < len(drill) and drill[dn] == drill[dn+1]:
        factor = mat_fac(2)
        del(drill[dn])
    else:
        factor = mat_fac(1)
    if dn == 0:
        drill[dn] += [factor]   
    else:
        drill[dn] += [mat_mult(factor, drill[dn-1][3])]
    dn += 1

# Locate trusty knights
for sn in range(L):
    kn = trusty_k[sn]
    row, col = kn//N+1, kn%N+1
    newpos = bin_s(row, col) 
    print(newpos[0], newpos[1])
                    


View More Similar Problems

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →