No.142 単なる配列の操作に関する実装問題

No.142 単なる配列の操作に関する実装問題 - yukicoder

  • 偶奇だけに着目すればよいので、ビット配列として扱えば高速化できる問題。
  • 解法は思いついたものの、とんでもなく実装に手間取った。自分の実装力のなさに衝撃を受けてしまった...。
class ArrayImplementationSimply
{
public:
    typedef unsigned long long ull;
    const int Block = 64;

    pair<int,int> i2b(int idx)
    {
            return make_pair(idx/Block, idx%Block);
    }
    // arry[0..2] を move 分 shift して、そのときの arry[1] の値を返す
    ull shift(const array<ull,3> &arry, int move)
    {
            if ( move == 0 )
                return arry[1];
            if ( move > 0 )
            {
                return (arry[1]<<move)|(arry[0]>>(Block-move));
            }
            else
            {
                move *= -1;
                return (arry[1]>>move)|(arry[2]<<(Block-move));
            }
    }
    void solve(void)
    {
            int N,S,X,Y,Z;
            int Q;
            cin>>N>>S>>X>>Y>>Z;
            cin>>Q;

            vector<ull> A(N/Block+1, 0);
            vector<ull> B(N/Block+1, 0);
            ull a;

            a = S;
            REP(i,N)
            {
                int p,b;
                tie(b,p) = i2b(i);
                if ( a%2 == 1 )
                    A[b] |= (1ULL<<p);
                a = (X*a+Y) % Z;
            }
            while (Q--)
            {
                int S,T,U,V;
                int sb,tb,ub,vb;
                int sp,tp,up,vp;

                cin>>S>>T>>U>>V;
                --S,--T,--U,--V;
                tie(sb,sp) = i2b(S);
                tie(tb,tp) = i2b(T);
                tie(ub,up) = i2b(U);
                tie(vb,vp) = i2b(V);

                // B=A[S,T]
                // A[k] = A[k] + B[k-U] (U<=k<=V)
                int move = up-sp;
                for (int k = 0, j = sb; k <= vb-ub; ++k, ++j)
                {
                    array<ull,3> C{0,0,0};// 隣接するブロックを一緒にシフト演算する

                    // 変換対象 block A[j] が C[1] にくるようにする。
                    for (int i = -1; i <= 1; ++i)
                    {   // copy 範囲外は 0 に
                        if ( sb <= i+j && i+j <= tb )
                            C[i+1] = A[i+j];
                        // 頭の不要な部分は削る
                        if ( i+j == sb )
                            C[i+1] &= ~((1ULL<<sp)-1);
                        // 末尾の不要な部分は削る
                        if ( i+j == tb )
                            C[i+1] &= ((1ULL<<tp)|((1ULL<<tp)-1));
                    }
                    // bit shift
                    B[k] = shift(C, move);
                }
                for (int k = ub; k <= vb; ++k)
                    A[k] ^= B[k-ub];
            }
            REP(i,N)
            {
                int p,b;
                tie(b,p) = i2b(i);
                if ( A[b] & (1ULL<<p) )
                    cout<<"O";
                else
                    cout<<"E";
            }
            cout<<endl;
    }
};