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

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 →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →