//generated by GPT-5.4?, modified by hamamu namespace MatSpace{ using ll=long long; template struct PlusTimesOps{ static T zero(){ return T(0); } static T one() { return T(1); } static T add(const T &a,const T &b){ return a+b; } static T mul(const T &a,const T &b){ return a*b; } }; template> struct mat_{ using value_type=T; using row_type=std::vector; using storage_type=std::vector; storage_type a; mat_(){} mat_(initializer_list> init): a(init.begin(),init.end()){ assert(all_of(a.begin(),a.end(),[&](const auto &row){ return (ll)row.size()==w(); })); } mat_(ll h,ll w,T x=Ops::zero()): a(h,row_type(w,x)){} mat_(ll n): mat_(n,n,Ops::zero()){} mat_(ll n,const string &tag): mat_(n,n,Ops::zero()){ if (tag=="E") *this=identity(n); } mat_(const std::vector &v,bool istranspose=false){ if (istranspose){ a.assign(1,row_type((ll)v.size(),Ops::zero())); for (ll j=0; j operator*(const std::vector &v) const { assert(w()==(ll)v.size()); std::vector ret(h(),Ops::zero()); for (ll i=0; i0; n>>=1,base*=base) if (n&1) ret*=base; return ret; } mat_ t() const { mat_ ret(w(),h(),Ops::zero()); for (ll i=0; i; /* mat m={{2,3,4},{1,0,5}}; mat m(2); //2x2正方行列、all0 mat m(2,"E"); //2x2単位行列 mat m(h,w); //h*w行列、all0 mat m(h,w,x); //h*w行列、allx mat m(v); //vectorを縦(n×1)のmat型に変換 mat m(v,true); //vectorを横(1×n)のmat型に変換 A+B A*B A+=B A*=B //Opsのadd,mulでの行列演算 vmll u=A*v //Opsのmulでの行列とベクトルの積 A-B A-=B -A //Opsを無視して加減算 A*k A*=k //Opsを無視して各要素をk倍 mat mm=m.pow(k); //m^k mat mm=m.t(); //転置 - ---- min-plus半環 (最短路計算など) struct MinPlusOpsLL{ static ll zero(){ return INF; } static ll one() { return 0; } static ll add(ll a,ll b){ return min(a,b); } static ll mul(ll a,ll b){ if(a>=INF || b>=INF) return INF; return min(INF,a+b); } }; using minmat = mat_; その他半環はメモ参照 */