Mixing proteins


Problem Statement :


Some scientists are working on protein recombination, and during their research, they have found a remarkable fact: there are 4 proteins in the protein ring that mutate after every second according to a fixed pattern. For simplicity, proteins are called  (you know, protein names can be very complicated). A protein mutates into another one depending on itself and the protein right after it. Scientists determined that the mutation table goes like this:


Here rows denote the protein at current position, while columns denote the protein at the next position. And the corresponding value in the table denotes the new protein that will emerge. So for example, if protein i is A, and protein i + 1 is B, protein i will change to B. All mutations take place simultaneously. The protein ring is seen as a circular list, so last protein of the list mutates depending on the first protein.

Using this data, they have written a small simulation software to get mutations second by second. The problem is that the protein rings can be very long (up to 1 million proteins in a single ring) and they want to know the state of the ring after upto  seconds. Thus their software takes too long to report the results. They ask you for your help.

Input Format

Input contains 2 lines.
First line has 2 integers  and ,  being the length of the protein ring and  the desired number of seconds.
Second line contains a string of length  containing uppercase letters ,,  or  only, describing the ring.

Output Format

Output a single line with a string of length , describing the state of the ring after  seconds.



Solution :



title-img


                            Solution in C :

In  C :






#include <stdio.h>
#include <stdlib.h>

int main() {
	int i, j, n, k, c, *prot, *protnew, p2;
	scanf("%d %d",&n,&k);
	prot = malloc(n * sizeof(int));
	protnew = malloc(n * sizeof(int));
	for (i=0; i<n; i++) {
		while (c=getchar()-'A') if (c>=0 && c<=3) break;
		prot[i] = c;
	}
	p2 = 1;
	while (p2<k) p2 <<= 1;
	while (p2 >>= 1) {
		if (p2 & k) {
			for (i=0; i<n; i++) protnew[i] = prot[i] ^ prot[(i+p2) % n];
			for (i=0; i<n; i++) prot[i] = protnew[i];
		}
	}
	for (i=0; i<n; i++) putchar('A' + prot[i]);
	putchar('\n');
	return 0;
}
                        


                        Solution in C++ :

In  C++  :






#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <vector>

using namespace std;

#define NMAX 1111111

char ch;
int A[2][NMAX];
int N, K, i, b, p, c, step;

int main() {
//	freopen("x.txt", "r", stdin);
	scanf("%d %d", &N, &K);
	for (i = 0; i < N; i++) {
		scanf(" %c", &ch);
		A[0][i] = ch - 'A';
	}

	for (c = 0, b = 30; b >= 0; b--)
		if (K & (1 << b)) {
			p = c;
			c = 1 - c;
			step = (1 << b) % N;
			for (i = 0; i < N; i++)
				A[c][i] = A[p][i] ^ A[p][(i + step) % N];
		}

	for (i = 0; i < N; i++)
		printf("%c", A[c][i] + 'A');
	printf("\n");
	return 0;
}
                    


                        Solution in Java :

In  Java  :







import java.io.*;

public class Solution {

    public static void solve(Input in, PrintWriter out) throws IOException {
        int n = in.nextInt(), k = in.nextInt();
        int[] a = new int[n];
        char[] c = in.next().toCharArray();
        for (int i = 0; i < n; ++i) {
            a[i] = c[i] - 'A';
        }
        for (int i = 1; i <= k; i *= 2) {
            if ((k & i) != 0) {
                int[] b = new int[n];
                for (int j = 0; j < n; ++j) {
                    b[j] = a[j] ^ a[(j + i) % n];
                }
                a = b;
            }
        }
        for (int i = 0; i < n; ++i) {
            c[i] = (char) (a[i] + 'A');
        }
        out.println(c);
    }

    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(System.out);
        solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);
        out.close();
    }

    static class Input {
        BufferedReader in;
        StringBuilder sb = new StringBuilder();

        public Input(BufferedReader in) {
            this.in = in;
        }

        public Input(String s) {
            this.in = new BufferedReader(new StringReader(s));
        }

        public String next() throws IOException {
            sb.setLength(0);
            while (true) {
                int c = in.read();
                if (c == -1) {
                    return null;
                }
                if (" \n\r\t".indexOf(c) == -1) {
                    sb.append((char)c);
                    break;
                }
            }
            while (true) {
                int c = in.read();
                if (c == -1 || " \n\r\t".indexOf(c) != -1) {
                    break;
                }
                sb.append((char)c);
            }
            return sb.toString();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :








# A = 0 (0b00)
# B = 1 (0b01)
# C = 2 (0b10)
# D = 3 (0b11)
# a[x + 2^m, i] = a[x, i] ^ a[x, i + 2^m]

import sys

c2i = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
i2c = ['A', 'B', 'C', 'D']

n, k = [int(x) for x in input().strip().split()]

s = [c2i[x] for x in input().strip()]
s = [s, [0] * len(s)]

a, b = 1, 0

while k > 0:
    # swap
    a ^= b
    b ^= a
    a ^= b
    
    # closest power of 2
    cp2 = 1
    for i in range(29, 0, -1):
        if k - (1 << i) >= 0:
            cp2 = 1 << i
            break
            
    k -= cp2
    
    for i in range(n):
        s[b][i] = s[a][i] ^ s[a][(i + cp2) % n]
        

for i in s[b]:
    sys.stdout.write(i2c[i])
    
sys.stdout.flush()
                    


View More Similar Problems

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 →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →