Question Link
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 a, B, c, d (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:
A B C D _ _ _ _A| A B C DB| B A D CC| C D A BD| D C B A
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 109 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 n and k, n being the length of the protein ring and K the desired number of seconds.
Second line contains a string of length N containing uppercase letters A, B, C or D only, describing the ring.
Output Format
Output a single line with a string of length N, describing the state of the ring after kseconds.
Constraints
1 ≤ n ≤106
1 ≤ k ≤ 109
Sample input:
5 15AAAAD
Sample output:
DDDDA
Explanation
The complete sequence of mutations is:
AAADDAADADADDDDDAAADDAADADADDDDDAAAADAADDDADDADDAADADAADDDADAADDAADADADDDDA
First, we can observe from the matrix that the "mutation" can be seen as an exclusive or of two values.
Then, by observing the mutation formula of the first few K, we can obtain that when K % 2 = 0, s [I] = s [I] ^ s [(I + k) % N];
If the preceding equation is not true, You can enumerate every bit of the binary value of K to convert it to the preceding situation.
For example, if K is 6, the binary value of K is 110, that is, it is changed to 4 s first, and then to 2 s later.
Accepted code:
1 #include <string> 2 #include <iostream> 3 using namespace std; 4 5 typedef long long LL; 6 #define rep(i, n) for (int i = (0); i < (n); i++) 7 8 string s; 9 int n, k, ch[2][1000050];10 int main(void) {11 ios::sync_with_stdio(false);12 while (cin >> n >> k) {13 cin >> s;14 rep (i, n) ch[0][i] = s[i] - ‘A‘;15 16 int c = 0;17 for (LL i = 1; i <= k; i <<= 1) if (i & k) {18 c ^= 1;19 rep (j, n) ch[c][j] = ch[c^1][j] ^ ch[c^1][(j + i) % n];20 }21 rep (i, n) s[i] = ch[c][i] + ‘A‘;22 cout << s << endl;23 }24 25 return 0;26 }
Hackerrank -- mixing proteins (math)