Problem:
Score : 700 points

Problem Statement

Given is a sequence of N digits a_1a_2\ldots a_N, where each element is 1, 2, or 3.
Let x_{i,j} defined as follows:

x_{1,j} := a_j \quad (1 \leq j \leq N)

x_{i,j} := | x_{i-1,j} - x_{i-1,j+1} | \quad (2 \leq i \leq N and 1 \leq j \leq N+1-i)

Find x_{N,1}.

Constraints

2 \leq N \leq 10^6

a_i = 1,2,3 (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
a_1a_2\ldotsa_N

Output

Print x_{N,1}.

Sample Input 1

4
1231

Sample Output 1

1

x_{1,1},x_{1,2},x_{1,3},x_{1,4} are respectively 1,2,3,1.

x_{2,1},x_{2,2},x_{2,3} are respectively |1-2| = 1,|2-3| = 1,|3-1| = 2.

x_{3,1},x_{3,2} are respectively |1-1| = 0,|1-2| = 1.

Finally, x_{4,1} = |0-1| = 1, so the answer is 1.

Sample Input 2

10
2311312312

Sample Output 2

0

Solution in C++14 (GCC 5.4.1) (judge verdict: Time Limit Exceeded)

#include<algorithm>
#include<iostream>
#include<vector>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdlib>
using namespace std;

static const int MAXN = 1000000;
int a[60000];
int n;
int c[MAXN];

int init(){
    for(int i = 50000; i < 59049; i++){
        int k = 19683;
        int b[10];
        int m = i;
        for(int j = 9; j >= 0; j--){
            b[j] = m / k;
            m -= b[j] * k;
            k /= 3;
        }
        for(int j = 0; j < 9; j++){
            for(int l = 0; l < 9 - j; l++){
                b[l] = fabs(b[l] - b[l+1]);
            }
        }
        a[i] = b[0];
    }
}

int solve(){
    int m;
    for(m = n; m >= 10; m -= 9){
        for(int i = 0; i <= m - 10; i++){
            int b = 0;
            int k = 1;
            for(int j = 0; j < 10; j++){
                b += c[i+j]*k;
                k *= 3;
            }
            c[i] = a[b];
        }
    }
    for(int i = 0; i < m-1; i++){
        for(int l = 0; l < m-1 - i; l++){
            c[l] = fabs(c[l] - c[l+1]);
        }        
    }
    return c[0];
}

int main(){
    init();

    cin >> n;
    string s;
    cin >> s;
    for(int i = 0; i < n; i++){
        c[i] = (int)(s[i] - '1');
    }

    cout << solve() << endl;

}