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

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →