Hackerrank--Mixing proteins(Math)

题目链接


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 D B| B A D C C| C D A B D| 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 KN 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,BC 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
1N106 
1K109

Sample Input:

5 15 AAAAD 

Sample Output:

DDDDA 

Explanation
The complete sequence of mutations is:

AAADD

AADAD

ADDDD

DAAAD

DAADA

DADDD

DDAAA

ADAAD

DDADD

ADDAA

DADAA

DDDAD

AADDA

ADADA

DDDDA
首先从矩阵可以观察到,“突变”可以看做是两个值的异或。
然后通过观察前几个k的突变公式,可以得到,当k%2==0时,就是 s[i] = s[i] ^ s[(i + k) % n];
对于上述等式不成立的k,可以通过枚举k的二进制的每一位,可以转化为上述情况。
如k=6,那么k的二进制是 110, 也就是先变成4s,然后再变成2s后。
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 }

 

 


                            

你可能感兴趣的:(Math)