#include #include #include #include #include #include using I=long long; static const I P=65537; static const int A[3][2]={{0,1},{1,0},{1,-1}}; static const int B[3][2]={{0,1},{1,0},{1,-1}}; static const int C[3][3]={{0,1,0},{1,1,-1},{1,0,0}}; static const int IA=2, OA=2; static I mod(I x){x%=P;return x<0?x+P:x;} struct Plan{I mul,add;int split;}; static std::map,Plan> cache; static Plan plan(int n,int m,int d){ auto key=std::make_tuple(n,m,d);auto it=cache.find(key); if(it!=cache.end())return it->second; Plan r{I(n)*m,I(n)*m-(n+m-1),0}; if(d>0 && std::min(n,m)>1){ int h=(std::max(n,m)+1)/2;auto q=plan(h,h,d-1); Plan c{3*q.mul,3*q.add+I(IA)*h+I(OA+2)*(2*h-1),1}; if(c.mul+c.add=2*std::min(n,m)){ int half=std::max(n,m)/2;Plan x,y;int extra; if(n>=m){x=plan(half,m,d);y=plan(n-half,m,d);extra=n-half+m-1;} else{x=plan(n,half,d);y=plan(n,m-half,d);extra=n+m-half-1;} Plan rect{x.mul+y.mul,x.add+y.add+extra,2}; if(rect.mul+rect.add=m?h+m-1:n+h-1),l2=(n>=m?n-h+m-1:n+m-h-1); I*left=work;I*right=left+l1;I*next=right+l2; if(n>=m){recurse(a,h,b,m,left,next,depth);recurse(a+h,n-h,b,m,right,next,depth);} else{recurse(a,n,b,h,left,next,depth);recurse(a,n,b+h,m-h,right,next,depth);} std::fill(z,z+n+m-1,0);std::copy(left,left+l1,z); for(int j=0;j8192||m>8192||d<0||d>20)return 1; if(!plan(n,m,d).split){base(a,n,b,m,out);return 0;} // Geometrically shrinking operands bound the arena by 32*n+128. std::vector workspace(32*std::max(n,m)+128); recurse(a,n,b,m,out,workspace.data(),d);return 0; }catch(...){return 2;} } static std::map,std::vector> rootcache; static I fpow(I a,I k,I*counter){I r=1;while(k){if(k&1){r=r*a%P;++counter[1];} k>>=1;if(k){a=a*a%P;++counter[1];}}return r;} static const std::vector& roots(int n,bool inv,I*counter){ auto key=std::make_pair(n,inv);auto it=rootcache.find(key);if(it!=rootcache.end())return it->second; I w=fpow(3,(P-1)/n,counter);if(inv)w=fpow(w,P-2,counter); std::vector r(n/2,1);for(int i=1;i&a,bool inv,I*counter){ int n=a.size();for(int i=1,j=0;i>1;for(;j&bit;bit>>=1)j^=bit;j^=bit;if(i8192||m>8192)return 1; counts[0]=counts[1]=0;counts[2]=1; int len=1,lg=0;while(len aa(len),bb(len);std::copy(a,a+n,aa.begin());std::copy(b,b+m,bb.begin()); transform(aa,false,counts);transform(bb,false,counts); for(int i=0;i