File size: 2,208 Bytes
aff9293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

#include <vector>
#include <array>
#include <map>
#include <tuple>
#include <algorithm>
#include <cstdint>
#include <stdexcept>
using I=long long;
using V=std::vector<I>;
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;bool split;};
static std::map<std::tuple<int,int,int>,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),false};
 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),true};
  if(c.mul+c.add<r.mul+r.add)r=c;
 }
 cache[key]=r;return r;
}
static V lin2(const V&a,const V&b,const int*r){
 V z(a.size());for(size_t i=0;i<a.size();++i)z[i]=mod(r[0]*a[i]+r[1]*b[i]);return z;
}
static V lin3(const std::array<V,3>&a,const int*r){
 V z(a[0].size());for(size_t i=0;i<z.size();++i)
 z[i]=mod(r[0]*a[0][i]+r[1]*a[1][i]+r[2]*a[2][i]);return z;
}
static V mul(const V&a,const V&b,int d){
 int n=a.size(),m=b.size();auto q=plan(n,m,d);
 if(!q.split){
  V z(n+m-1);for(int t=0;t<n+m-1;++t){
   int lo=std::max(0,t-m+1),hi=std::min(n-1,t);
   I s=a[lo]*b[t-lo];for(int j=lo+1;j<=hi;++j)s+=a[j]*b[t-j];z[t]=mod(s);
  }return z;
 }
 int h=(std::max(n,m)+1)/2;V a0(h),a1(h),b0(h),b1(h);
 for(int i=0;i<n;++i)(i<h?a0[i]:a1[i-h])=a[i];
 for(int i=0;i<m;++i)(i<h?b0[i]:b1[i-h])=b[i];
 std::array<V,3> p;
 for(int t=0;t<3;++t)p[t]=mul(lin2(a0,a1,A[t]),lin2(b0,b1,B[t]),d-1);
 std::array<V,3> c;for(int t=0;t<3;++t)c[t]=lin3(p,C[t]);
 V z(4*h-1);std::copy(c[0].begin(),c[0].end(),z.begin());
 for(int t=1;t<3;++t)for(int j=0;j<2*h-1;++j)z[t*h+j]=mod(z[t*h+j]+c[t][j]);
 z.resize(n+m-1);return z;
}
extern "C" int sorilun_mul(const I*a,int n,const I*b,int m,int d,I*out){
 try{
  if(n<1||m<1||n>8192||m>8192||d<0||d>20)return 1;
  V av(a,a+n),bv(b,b+m);auto z=mul(av,bv,d);std::copy(z.begin(),z.end(),out);return 0;
 }catch(...){return 2;}
}
extern "C" void sorilun_clear_cache(){cache.clear();}