#ifndef INCLUDE_MODE #define INCLUDE_MODE // #define REACTIVE // #define USE_GETLINE #endif #ifdef INCLUDE_MAIN IN VO Solve() { CIN( int , N ); int M = N - 1; gE.resize( N ); FOR( j , 0 , M ){ CIN_ASSERT( uj , 1 , N ); CIN_ASSERT( vj , 1 , N ); uj--; vj--; gE[uj].push_back( vj ); gE[vj].push_back( uj ); } gA.resize( N ); FOR( i , 0 , N ){ CIN( ll , Ai ); gA[i] = Ai; } Graph tree{ N , Get( gE ) }; DepthFirstSearchOnTree dfst{ tree }; // a[0]:左端が増大する{列の個数,門松度の合計} // a[1]:左端が減少する{列の個数,門松度の合計} // a[2]:左端が変化なし{列の個数,門松度の合計} using T = vector>; auto ADD = [&]( const T& t0 , const T& t1 ) { return T{ { t0[0][0] + t1[0][0] , t0[0][1] + t1[0][1] } , { t0[1][0] + t1[1][0] , t0[1][1] + t1[1][1] }, { t0[2][0] + t1[2][0] , t0[2][1] + t1[2][1] } }; }; auto END = [&]( const T& t , const int& i ){ return ADD( t , {{0,0},{0,0},{1,0}}); }; auto UPDATE = [&](const T& t,const bool&,const int& i,const int& j) { return gA[j] < gA[i] ? T{ { 0 , 0 } , { t[0][0] + t[1][0] + t[2][0] , t[0][0] + t[0][1] + t[1][1] + t[2][1] } , { 0 , 0 } } : gA[j] > gA[i] ? T{ { t[0][0] + t[1][0] + t[2][0] , t[0][1] + t[1][0] + t[1][1] + t[2][1] } , { 0 , 0 } , { 0 , 0 } } : T{ { 0 , 0 } , { 0 , 0 } , { t[0][0] + t[1][0] + t[2][0] , t[0][1] + t[1][1] + t[2][1] } }; }; AbstractMonoid monoid{ ADD , T{3,{0,0}} }; vector d; dfst.RerootingDP( monoid , END , UPDATE , d ); MP answer = 0; FOR( i , 0 , N ){ answer += d[i][0][1] + d[i][1][1] + d[i][2][1]; } answer /= 2; RETURN( answer ); } REPEAT_MAIN(1); #else // INCLUDE_MAIN #ifdef INCLUDE_SUB // グラフ用 TE Map gF; TE VE gA; TE VE> gE; TE TY V> IN auto Get( CO V& a ) { return [&]( CRI i = 0 ){ RE a[i]; }; } // COMPAREに使用。圧縮時は削除する。 ll Naive( int N , int M , int K ) { ll answer = N + M + K; return answer; } // COMPAREに使用。圧縮時は削除する。 ll Answer( ll N , ll M , ll K ) { // START_WATCH; ll answer = N + M + K; // // TLに準じる乱択や全探索。デフォルトの猶予は100.0[ms]。 // CEXPR( double , TL , 2000.0 ); // while( CHECK_WATCH( TL ) ){ // } return answer; } // 圧縮時は中身だけ削除する。 IN VO Experiment() { // CEXPR( int , bound , 10 ); // FOREQ( N , 0 , bound ){ // FOREQ( M , 0 , bound ){ // FOREQ( K , 0 , bound ){ // COUT( N , M , K , ":" , Naive( N , M , K ) ); // } // } // // cout << Naive( N ) << ",\n"[N==bound]; // } } // 圧縮時は中身だけ削除する。 IN VO SmallTest() { // CEXPR( int , bound , 10 ); // FOREQ( N , 0 , bound ){ // FOREQ( M , 0 , bound ){ // FOREQ( K , 0 , bound ){ // COMPARE( N , M , K ); // } // } // // COMPARE( N ); // } } #define INCLUDE_MAIN #include __FILE__ #else // INCLUDE_SUB #ifdef INCLUDE_LIBRARY /* C-x 3 C-x o C-x C-fによるファイル操作用 BFS: c:/Users/user/Documents/Programming/Mathematics/Geometry/Graph/BreadthFirstSearch/compress.txt CoordinateCompress: c:/Users/user/Documents/Programming/Mathematics/SetTheory/DirectProduct/CoordinateCompress/compress.txt DFSOnTree c:/Users/user/Documents/Programming/Mathematics/Geometry/Graph/DepthFirstSearch/Tree/a.hpp Divisor: c:/Users/user/Documents/Programming/Mathematics/Arithmetic/Prime/Divisor/compress.txt IntervalAddBIT c:/Users/user/Documents/Programming/Mathematics/SetTheory/DirectProduct/AffineSpace/BIT/IntervalAdd/compress.txt Polynomial c:/Users/user/Documents/Programming/Mathematics/Polynomial/compress.txt UnionFind c:/Users/user/Documents/Programming/Mathematics/Geometry/Graph/UnionFindForest/compress.txt */ // VVV 常設でないライブラリは以下に挿入する。 // 構築 O(1)/O(|V_G|)(未初期化/初期化) // Next()の反復でinitから到達可能な頂点を全探索 O(initの連結成分における辺の本数) // Next()の反復とShift()で全探索 O(|V_G|+|E_G|) // initからの到達可能性判定と深さ計算 O(initの連結成分における辺の本数) // 連結成分の色分けと数え上げ O(|V_G|+|E_G|) template class VirtualBreadthFirstSearch : public PointedSet { protected: GRAPH& m_G; bool m_initialised; // 次の探索点たちを格納。 list m_next; // 到達済みか否かを格納。 vector m_found; // 到達済みかつ到達済みの点から辺を辿って到達した場合、その点を格納。 vector m_prev; public: inline VirtualBreadthFirstSearch( GRAPH& G ); inline VirtualBreadthFirstSearch( GRAPH& G , const int& init ); // m_nextとm_foundとm_prevを初期化する。 inline void Initialise(); // m_nextとm_foundとm_prevを初期化した上でinitを最初の探索点に設定する。 inline void Initialise( const int& init ); // m_nextを初期化した上でm_foundとm_prevを非初期化せずinitを次の探索点に設定する。 inline void Shift( const int& init ); inline const int& size() const noexcept; inline vector::reference found( const int& i ); inline const int& prev( const int& i ); inline int Next(); // 最初の未到達点(初期化時点ではinit)から到達できる未到達点の深さを格納し、 // 到達できない未到達点や既到達点は深さの代わりに-1を格納。 void SetDepth( vector& depth ); // 無向グラフである場合にのみサポート。 // 未到達点の全体のなす部分グラフにおける連結成分の色分けと連結成分数を格納。 void SetConnectedComponent( vector& cc_num , int& count ); private: virtual void Push( list& next , const int& i ) = 0; }; template class BreadthFirstSearch : public VirtualBreadthFirstSearch { public: template inline BreadthFirstSearch( GRAPH& G , const Args&... args ); private: inline void Push( list& next , const int& i ); }; template inline VirtualBreadthFirstSearch::VirtualBreadthFirstSearch( GRAPH& G ) : m_G( G ) , m_initialised( false ) , m_next() , m_found() , m_prev() { static_assert( is_same_v,int> ); } template inline VirtualBreadthFirstSearch::VirtualBreadthFirstSearch( GRAPH& G , const int& init ) : VirtualBreadthFirstSearch( G ) { Initialise( init ); } template template inline BreadthFirstSearch::BreadthFirstSearch( GRAPH& G , const Args&... args ) : VirtualBreadthFirstSearch( G , args... ) {} template inline void VirtualBreadthFirstSearch::Initialise() { m_initialised = true; const int& V = size(); m_next.clear(); m_found = vector( V ); m_prev = vector( V , -1 ); } template inline void VirtualBreadthFirstSearch::Initialise( const int& init ) { assert( ( this->init() = init ) < size() ); Initialise(); m_next.push_back( init ); m_found[init] = true; } template inline void VirtualBreadthFirstSearch::Shift( const int& init ) { if( m_initialised ){ const int& V = size(); assert( ( this->init() = init ) < V ); m_next.clear(); if( ! m_found[init] ){ m_next.push_back( init ); m_found[init] = true; } } else { Initialise( init ); } } template inline const int& VirtualBreadthFirstSearch::size() const noexcept { return m_G.size(); } template inline vector::reference VirtualBreadthFirstSearch::found( const int& i ) { assert( i < size() ); if( !m_initialised ){ Initialise(); } return m_found[i]; } template inline const int& VirtualBreadthFirstSearch::prev( const int& i ) { assert( i < size() ); if( !m_initialised ){ Initialise(); } return m_prev[i]; } template inline int VirtualBreadthFirstSearch::Next() { if( m_next.empty() ){ return -1; } const int i_curr = m_next.front(); m_next.pop_front(); auto&& edge = m_G.Edge( i_curr ); while( ! edge.empty() ){ const int& i = edge.front(); auto&& found_i = m_found[i]; if( ! found_i ){ Push( m_next , i ); m_prev[i] = i_curr; found_i = true; } edge.pop_front(); } return i_curr; } template void VirtualBreadthFirstSearch::SetDepth( vector& depth ) { depth = vector( size() , -1 ); int i = Next(); depth[i] = 0; while( ( i = Next() ) != -1 ){ depth[i] = depth[prev( i )] + 1; } return; } template void VirtualBreadthFirstSearch::SetConnectedComponent( vector& cc_num , int& count ) { const int& V = size(); cc_num = vector( V , -1 ); count = 0; for( int i = 0 ; i < V ; i++ ){ if( cc_num[i] == -1 ){ Shift( i ); int j = Next(); if( j != -1 ){ while( j != -1 ){ // 無向グラフである場合は常にtrue。 assert( cc_num[j] == -1 ); cc_num[j] = count; j = Next(); } count++; } } } return; } template inline void BreadthFirstSearch::Push( list& next , const int& i ) { next.push_back( i ); } template class DepthFirstSearch : public VirtualBreadthFirstSearch { public: template inline DepthFirstSearch( GRAPH& G , const Args&... args ); private: inline void Push( list& next , const int& i ); }; template template inline DepthFirstSearch::DepthFirstSearch( GRAPH& G , const Args&... args ) : VirtualBreadthFirstSearch( G , args... ) {} template inline void DepthFirstSearch::Push( list& next , const int& i ) { next.push_front( i ); } // digitはAncestorとLCAにのみ使用。普段は0で良い。 // 2^16 = 65536 // 2^17 = 131072 // 2^18 = 262144 // Gが無向グラフとしての木である場合にのみサポート。 template class DepthFirstSearchOnTree : public DepthFirstSearch { private: vector m_reversed; vector> m_children; vector m_children_num; bool m_set_children; vector m_depth; bool m_set_depth; vector m_height; bool m_set_height; vector m_weight; bool m_set_weight; int m_digit; vector> m_doubling; bool m_set_doubling; public: inline DepthFirstSearchOnTree( TREE& T , const int& root = 0 , const int& digit = 0 ); inline void Initialise( ) = delete; inline void Initialise( const int& init ) = delete; inline void Shift( const int& init ) = delete; inline const int& Root() const; inline const int& Parent( const int& i ); inline const vector& Children( const int& i ); inline const int& Depth( const int& i ); inline const int& Height( const int& i ); inline const int& Weight( const int& i ); // 探索順にノードを番号づける。 inline const int& NodeNumber( const int& i , const bool& reversed = false ) const; // 共通の親を持つノード間で昇順に番号づける。 inline const int& ChildrenNumber( const int& i ); // 各ノードの高さ < 2^digitの場合のみサポート。 // n階の親Parent^n( i )を返す。 int Ancestor( int i , int n ); int LCA( int i , int j ); // LCAからi,j側に進める場合に進んだ先の頂点のラベルをi_prev,j_prevに格納する。 int LCA( int i , int j , int& i_prev , int& j_prev ); // Uを適当な型とし、 // Fは写像f:U^{< \omega} \times N -> Uに相当する型。 // 型推論のためにfはデフォルト引数で呼び出し可能とする。 // 入力の範囲内で要件 // (2) 任意の非負整数n,iとTの要素のみからなる任意の長さnの任意の列(u1,...,un)と // その並び換え(v1,...,vn)に対しf((u1,...,un),i)=f((v1,...,vn),i)である。 // を満たす場合のみサポート。 // dp[j] = f(jの子ノードkを渡るdp[k]の列,j) // を満たす配列dpの根での値dp[m_init]をO(m_V)で求める。 template ret_t RootingDP( F& f ); // Uを適当な型とし、 // Fは写像f:U \times N -> Uに相当する型。 // Eは写像g:U \times \{0,1\} \times N^2 -> Uに相当する型。 // 入力の範囲内で要件 // (1) MがUのモノイド構造である。(以下演算を*と置く) // (2) 任意の非負整数n,iとTの要素のみからなる任意の長さnの任意の列(u1,...,un)と // その並び換え(v1,...,vn)に対し // f(u1*u2*...*un,j)=f(v1*v2*...*vn,j)である。 // を満たす場合のみサポート。 // dp[i][j] = // f(iを根とみなした時のjの子ノードkを渡るg(dp[i][k],jはiの子孫,k,j)のMに関する積,j) // を満たす二重配列dpの対角成分dp[i][i]をO(|V_T|)で求めてdに格納する。 template void RerootingDP( MONOID M , F& f , G& g , vector>& d ); // fはノードjごとのデータ(グラフ構造に依存しない)、gは有向辺b?(j,k):(k,j)ごとのデータに対応。 // 例えば「パスの数」を求める時はm_Tが和、fが+1(葉かどうかに関係ない)、gがidでよい。 private: void SetChildren(); void SetDepth(); void SetHeight(); void SetWeight(); // 各ノードの高さ < 2^digitの場合のみサポート。 // LCA()を呼ぶ前にAncestor()経由で完全にダブリングを設定するため、 // 遅延評価してしまう // ../../../../Mathematics/Function/Iteration/Doubling/ // のダブリングでは代用しない。 void SetDoubling(); }; template inline DepthFirstSearchOnTree::DepthFirstSearchOnTree( TREE& T , const int& root , const int& digit ) : DepthFirstSearch( T , root ) , m_reversed( this->size() ) , m_children() , m_set_children() , m_depth() , m_set_depth() , m_height() , m_set_height() , m_weight() , m_set_weight() , m_digit( digit ) , m_doubling( m_digit ) , m_set_doubling() { int n = this->size(); while( --n >= 0 ){ m_reversed[n] = this->Next(); } } template inline const int& DepthFirstSearchOnTree::Root() const { return this->init(); } template inline const int& DepthFirstSearchOnTree::Parent( const int& i ) { return this->prev( i ); } template inline const vector& DepthFirstSearchOnTree::Children( const int& i ) { if( ! m_set_children ){ SetChildren(); } return m_children[i]; } template inline const int& DepthFirstSearchOnTree::Depth( const int& i ) { if( ! m_set_depth ){ SetDepth(); } return m_depth[i]; } template inline const int& DepthFirstSearchOnTree::Height( const int& i ) { if( ! m_set_height ){ SetHeight(); } return m_height[i]; } template inline const int& DepthFirstSearchOnTree::Weight( const int& i ) { if( ! m_set_weight ){ SetWeight(); } return m_weight[i]; } template inline const int& DepthFirstSearchOnTree::NodeNumber( const int& i , const bool& reversed ) const { return m_reversed[reversed ? i : this->size() - 1 - i]; } template inline const int& DepthFirstSearchOnTree::ChildrenNumber( const int& i ) { if( ! m_set_children ){ SetChildren(); } return m_children_num[i]; } template int DepthFirstSearchOnTree::Ancestor( int i , int n ) { if( ! m_set_doubling ){ SetDoubling(); } assert( ( n >> m_digit ) == 0 ); int d = 0; while( n != 0 ){ if( ( n & 1 ) == 1 ){ assert( ( i = m_doubling[d][i] ) != -1 ); } d++; n >>= 1; } return i; } template int DepthFirstSearchOnTree::LCA( int i , int j ) { int diff = Depth( i ) - Depth( j ); if( diff < 0 ){ swap( i , j ); diff *= -1; } i = Ancestor( i , diff ); if( i == j ){ return i; } int d = m_digit; while( --d >= 0 ){ const vector& doubling_d = m_doubling[d]; const int& doubling_d_i = doubling_d[i]; const int& doubling_d_j = doubling_d[j]; if( doubling_d_i != doubling_d_j ){ i = doubling_d_i; j = doubling_d_j; assert( i != -1 ); assert( j != -1 ); } } return Parent( i ); } template int DepthFirstSearchOnTree::LCA( int i , int j , int& i_prev , int& j_prev ) { if( i == j ){ i_prev = j_prev = -1; return i; } int diff = Depth( i ) - Depth( j ); if( diff < 0 ){ return LCA( j , i , j_prev , i_prev ); } if( diff > 0 ){ i_prev = Ancestor( i , diff - 1 ); i = Parent( i_prev ); assert( i != -1 ); if( i == j ){ j_prev = -1; return i; } } else if( ! m_set_doubling ){ SetDoubling(); } int d = m_digit; while( --d >= 0 ){ const vector& doubling_d = m_doubling[d]; const int& doubling_d_i = doubling_d[i]; const int& doubling_d_j = doubling_d[j]; if( doubling_d_i != doubling_d_j ){ i = doubling_d_i; j = doubling_d_j; assert( i != -1 ); assert( j != -1 ); } } i_prev = i; j_prev = j; return Parent( i_prev ); } template void DepthFirstSearchOnTree::SetChildren() { assert( !m_set_children ); m_set_children = true; const int& V = this->size(); m_children.resize( V ); m_children_num.resize( V ); for( int i = 0 ; i < V ; i++ ){ const int& j = Parent( i ); if( j == -1 ){ m_children_num[i] = -1; } else { vector& m_children_j = m_children[j]; m_children_num[i] = m_children_j.size(); m_children_j.push_back( i ); } } return; } template void DepthFirstSearchOnTree::SetDepth() { assert( !m_set_depth ); m_set_depth = true; const int& V = this->size(); m_depth.resize( V ); for( int i = 0 ; i < V ; i++ ){ const int& reversed_i = m_reversed[i]; const int& parent_i = Parent( reversed_i ); if( parent_i != -1 ){ m_depth[i] += m_depth[parent_i] + 1; } } return; } template void DepthFirstSearchOnTree::SetHeight() { assert( !m_set_height ); m_set_height = true; const int& V = this->size(); m_height.resize( V ); for( int i = 0 ; i < V ; i++ ){ const int& reversed_i = m_reversed[i]; const int& parent_i = Parent( reversed_i ); if( parent_i != -1 ){ int& height_parent_i = m_height[parent_i]; const int& height_i = m_height[reversed_i]; height_parent_i > height_i ? height_parent_i : height_parent_i = height_i + 1; } } return; } template void DepthFirstSearchOnTree::SetWeight() { assert( !m_set_weight ); m_set_weight = true; const int& V = this->size(); m_weight.resize( V ); for( int i = 0 ; i < V ; i++ ){ const int& reversed_i = m_reversed[i]; const int& parent_i = Parent( reversed_i ); if( parent_i != -1 ){ m_weight[parent_i] += m_weight[reversed_i] + 1; } } return; } template void DepthFirstSearchOnTree::SetDoubling() { assert( !m_set_doubling ); m_set_doubling = true; const int& V = this->size(); { vector& doubling_0 = m_doubling[0]; doubling_0.reserve( V ); const int& r = Root(); for( int i = 0 ; i < V ; i++ ){ doubling_0.push_back( Parent( i ) ); } } for( int d = 1 ; d < m_digit ; d++ ){ vector& doubling_d = m_doubling[d]; vector& doubling_d_minus = m_doubling[d-1]; doubling_d.reserve( V ); for( int i = 0 ; i < V ; i++ ){ const int& doubling_d_minus_i = doubling_d_minus[i]; doubling_d.push_back( doubling_d_minus_i == -1 ? -1 : doubling_d_minus[doubling_d_minus_i] ); } } return; } template template ret_t DepthFirstSearchOnTree::RootingDP( F& f ) { using U = ret_t; static_assert( is_invocable_r_v,int> ); if( ! m_set_children ){ SetChildren(); } const int& V = this->size(); vector> children_value( V ); U temp; for( int n = 0 ; n < V ; n++ ){ const int& i = NodeNumber( n , true ); const int& j = Parent( i ); temp = f( children_value[i] , i ); if( j != -1 ){ children_value[j].push_back( temp ); } } return temp; } template template void DepthFirstSearchOnTree::RerootingDP( MONOID M , F& f , G& g , vector>& d ) { using U = inner_t; static_assert( is_invocable_r_v && is_invocable_r_v ); if( ! m_set_children ){ SetChildren(); } const int& V = this->size(); const U& e = M.Unit(); d.resize( V ); // children_value[i][m]にiのm番目の子ノードjまでの計算値のfでの像を格納。 vector> children_value( V ); // left_sum[i][m]にchildren_value[i][0],...,children_value[i][m-1]の // gでの像のMに関する積を格納。 vector> left_sum( V ); // right_sum[i][m]にchildren_value[i][m+1],...,children_value[i][size_i-1]の // gでの像のM関する積を格納。 vector> right_sum( V ); for( int i = 0 ; i < V ; i++ ){ children_value[i].resize( m_children[i].size() ); } for( int n = 0 ; n < V ; n++ ){ const int& i = NodeNumber( n , true ); const vector& children_value_i = children_value[i]; const int size_i = children_value_i.size(); U temp = e; vector& left_sum_i = left_sum[i]; left_sum_i.reserve( size_i + 1 ); left_sum_i.push_back( temp ); for( int m = 0 ; m < size_i ; m++ ){ left_sum_i.push_back( temp = M.Product( temp , g( children_value_i[m] , true , i , m_children[i][m] ) ) ); } const int& j = Parent( i ); if( j != -1 ){ children_value[j][m_children_num[i]] = f( temp , i ); } temp = e; vector& right_sum_i = right_sum[i]; right_sum_i.resize( size_i ); for( int m = 1 ; m <= size_i ; m++ ){ right_sum_i[ size_i - m ] = temp; temp = M.Product( g( children_value_i[size_i - m] , true , i , m_children[i][size_i - m] ) , temp ); } } // left_sum[i][m]にchildren_value[i][0],...,children_value[i][m-1]の // gでの像のMに関する積を格納していたが、さらにこれに親ノードの寄与も追加する。 for( int n = 1 ; n < V ; n++ ){ const int& i = NodeNumber( n ); const int& j = Parent( i ); const int& k = ChildrenNumber( i ); vector& left_sum_i = left_sum[i]; vector& right_sum_i = right_sum[i]; const int size_i = right_sum_i.size(); // children_value[j][0],...,children_value[j][k-1]のgでの像と // rest_j(既に計算済み)と // children_value[j][k+1],...,children_value[j][size_i-1]のgでの像と // のMに関する積のfでの像のgでの像。 const U rest_i = g( f( M.Product( left_sum[j][k] , right_sum[j][k] ) , j ) , false , i , j ); for( int m = 0 ; m <= size_i ; m++ ){ // left_sum_imにrest_iと // children_value[i][0],...,children_value[i][m-1]のgでの像 // のMに関する積を格納。 U& left_sum_im = left_sum_i[m]; left_sum_im = M.Product( rest_i , left_sum_im ); } } for( int i = 0 ; i < V ; i++ ){ // left_sum[i].back()はchildren_value_i[0],...,children_value_i[size_i-1]の // gでの像と親の寄与のMに関する積。 d[i] = f( left_sum[i].back() , i ); } return; } // AAA 常設でないライブラリは以上に挿入する。 #define INCLUDE_SUB #include __FILE__ #else // INCLUDE_LIBRARY #ifdef DEBUG #define _GLIBCXX_DEBUG #define REPEAT_MAIN( BOUND ) START_MAIN; signal( SIGABRT , &AlertAbort ); AutoCheck( exec_mode , use_getline ); if( exec_mode == sample_debug_mode || exec_mode == submission_debug_mode || exec_mode == library_search_mode ){ RE 0; } else if( exec_mode == experiment_mode ){ Experiment(); RE 0; } else if( exec_mode == small_test_mode ){ SmallTest(); RE 0; }; DEXPR( int , bound_test_case_num , BOUND , min( BOUND , 100 ) ); int test_case_num = 1; if( exec_mode == solve_mode ){ if CE( bound_test_case_num > 1 ){ SET_ASSERT( test_case_num , 1 , bound_test_case_num ); } } else if( exec_mode == random_test_mode ){ CERR( "ランダムテストを行う回数を指定してください。" ); SET_LL( test_case_num ); } FINISH_MAIN #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , DEBUG_VALUE ) #define ASSERT( A , MIN , MAX ) CERR( "ASSERTチェック: " , ( MIN ) , ( ( MIN ) <= A ? "<=" : ">" ) , A , ( A <= ( MAX ) ? "<=" : ">" ) , ( MAX ) ); AS( ( MIN ) <= A && A <= ( MAX ) ) #define SET_ASSERT( A , MIN , MAX ) if( exec_mode == solve_mode ){ SET_LL( A ); ASSERT( A , MIN , MAX ); } else if( exec_mode == random_test_mode ){ CERR( #A , " = " , ( A = GetRand( MIN , MAX ) ) ); } else { AS( false ); } #define SOLVE_ONLY ST_AS( __FUNCTION__[0] == 'S' ) #define CERR( ... ) VariadicCout( cerr , __VA_ARGS__ ) << endl #define COUT( ... ) VariadicCout( cout << "出力: " , __VA_ARGS__ ) << endl #define CERR_A( A , N ) OUTPUT_ARRAY( cerr , A , N ) << endl #define COUT_A( A , N ) cout << "出力: "; OUTPUT_ARRAY( cout , A , N ) << endl #define CERR_ITR( A ) OUTPUT_ITR( cerr , A ) << endl #define COUT_ITR( A ) cout << "出力: "; OUTPUT_ITR( cout , A ) << endl #else #pragma GCC optimize ( "O3" ) #pragma GCC optimize ( "unroll-loops" ) #pragma GCC target ( "sse4.2,fma,avx2,popcnt,lzcnt,bmi2" ) #define REPEAT_MAIN( BOUND ) START_MAIN; CEXPR( int , bound_test_case_num , BOUND ); int test_case_num = 1; if CE( bound_test_case_num > 1 ){ SET_ASSERT( test_case_num , 1 , bound_test_case_num ); } FINISH_MAIN #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , VALUE ) #define ASSERT( A , MIN , MAX ) AS( ( MIN ) <= A && A <= ( MAX ) ) #define SET_ASSERT( A , MIN , MAX ) SET_LL( A ); ASSERT( A , MIN , MAX ) #define SOLVE_ONLY #define CERR( ... ) #define COUT( ... ) VariadicCout( cout , __VA_ARGS__ ) << ENDL #define CERR_A( A , N ) #define COUT_A( A , N ) OUTPUT_ARRAY( cout , A , N ) << ENDL #define CERR_ITR( A ) #define COUT_ITR( A ) OUTPUT_ITR( cout , A ) << ENDL #endif #ifdef REACTIVE #define ENDL endl #else #define ENDL "\n" #endif #ifdef USE_GETLINE #define SET_LL( A ) { GETLINE( A ## _str ); A = stoll( A ## _str ); } #define GETLINE_SEPARATE( SEPARATOR , ... ) SOLVE_ONLY; string __VA_ARGS__; VariadicGetline( cin , SEPARATOR , __VA_ARGS__ ) #define GETLINE( ... ) SOLVE_ONLY; GETLINE_SEPARATE( '\n' , __VA_ARGS__ ) #else #define SET_LL( A ) cin >> A #define CIN( LL , ... ) SOLVE_ONLY; LL __VA_ARGS__; VariadicCin( cin , __VA_ARGS__ ) #define SET_A( A , N ) SOLVE_ONLY; FOR( VARIABLE_FOR_CIN_A , 0 , N ){ cin >> A[VARIABLE_FOR_CIN_A]; } #define CIN_A( LL , A , N ) VE A( N ); SET_A( A , N ); #endif #include using namespace std; #define ATT __attribute__( ( target( "sse4.2,fma,avx2,popcnt,lzcnt,bmi2" ) ) ) #define START_MAIN int main(){ ios_base::sync_with_stdio( false ); cin.tie( nullptr ) #define FINISH_MAIN REPEAT( test_case_num ){ if CE( bound_test_case_num > 1 ){ CERR( "testcase " , VARIABLE_FOR_REPEAT_test_case_num , ":" ); } Solve(); CERR( "" ); } } #define START_WATCH chrono::system_clock::time_point watch = chrono::system_clock::now() #define CURRENT_TIME static_cast( chrono::duration_cast( chrono::system_clock::now() - watch ).count() / 1000.0 ) #define CHECK_WATCH( TL_MS ) ( CURRENT_TIME < TL_MS - 100.0 ) #define CEXPR( LL , BOUND , VALUE ) CE LL BOUND = VALUE #define CIN_ASSERT( A , MIN , MAX ) decldecay_t( MAX ) A; SET_ASSERT( A , MIN , MAX ) #define FOR( VAR , INITIAL , FINAL_PLUS_ONE ) for( decldecay_t( FINAL_PLUS_ONE ) VAR = INITIAL ; VAR < FINAL_PLUS_ONE ; VAR ++ ) #define FOREQ( VAR , INITIAL , FINAL ) for( decldecay_t( FINAL ) VAR = INITIAL ; VAR <= FINAL ; VAR ++ ) #define FOREQINV( VAR , INITIAL , FINAL ) for( decldecay_t( INITIAL ) VAR = INITIAL ; VAR + 1 > FINAL ; VAR -- ) #define AUTO_ITR( ARRAY ) auto itr_ ## ARRAY = ARRAY .BE() , end_ ## ARRAY = ARRAY .EN() #define FOR_ITR( ARRAY ) for( AUTO_ITR( ARRAY ) , itr = itr_ ## ARRAY ; itr_ ## ARRAY != end_ ## ARRAY ; itr_ ## ARRAY ++ , itr++ ) #define REPEAT( HOW_MANY_TIMES ) FOR( VARIABLE_FOR_REPEAT_ ## HOW_MANY_TIMES , 0 , HOW_MANY_TIMES ) #define SET_PRECISION( DECIMAL_DIGITS ) cout << fixed << setprecision( DECIMAL_DIGITS ) #define OUTPUT_ARRAY( OS , A , N ) FOR( VARIABLE_FOR_OUTPUT_ARRAY , 0 , N ){ OS << A[VARIABLE_FOR_OUTPUT_ARRAY] << (VARIABLE_FOR_OUTPUT_ARRAY==N-1?"":" "); } OS #define OUTPUT_ITR( OS , A ) { auto ITERATOR_FOR_OUTPUT_ITR = A.BE() , EN_FOR_OUTPUT_ITR = A.EN(); bool VARIABLE_FOR_OUTPUT_ITR = ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR; WH( VARIABLE_FOR_OUTPUT_ITR ){ OS << *ITERATOR_FOR_COUT_ITR; ( VARIABLE_FOR_OUTPUT_ITR = ++ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR ) ? OS : OS << " "; } } OS #define RETURN( ... ) SOLVE_ONLY; COUT( __VA_ARGS__ ); RE #define COMPARE( ... ) auto naive = Naive( __VA_ARGS__ ); auto answer = Answer( __VA_ARGS__ ); bool match = naive == answer; COUT( "(" , #__VA_ARGS__ , ") == (" , __VA_ARGS__ , ") : Naive == " , naive , match ? "==" : "!=" , answer , "== Answer" ); if( !match ){ RE; } // 圧縮用 #define TE template #define TY typename #define US using #define ST static #define AS assert #define IN inline #define CL class #define PU public #define OP operator #define CE constexpr #define CO const #define NE noexcept #define RE return #define WH while #define VO void #define VE vector #define LI list #define BE begin #define EN end #define SZ size #define LE length #define PW Power #define MO move #define TH this #define CRI CO int& #define CRUI CO uint& #define CRL CO ll& #define ST_AS static_assert #define reMO_CO remove_const #define is_COructible_v is_constructible_v #define rBE rbegin #define reSZ // 型のエイリアス #define decldecay_t( VAR ) decay_t TE US ret_t = decltype( declval()( declval()... ) ); TE US inner_t = TY T::type; US uint = unsigned int; US ll = long long; US ull = unsigned long long; US ld = long double; US lld = __float128; TE US T2 = pair; TE US T3 = tuple; TE US T4 = tuple; US path = pair; // 入出力用 TE IN basic_istream& VariadicCin( basic_istream& is ) { RE is; } TE IN basic_istream& VariadicCin( basic_istream& is , Arg& arg , ARGS&... args ) { RE VariadicCin( is >> arg , args... ); } TE IN basic_istream& VariadicGetline( basic_istream& is , CO char& separator ) { RE is; } TE IN basic_istream& VariadicGetline( basic_istream& is , CO char& separator , Arg& arg , ARGS&... args ) { RE VariadicGetline( getline( is , arg , separator ) , separator , args... ); } TE IN basic_ostream& operator<<( basic_ostream& os , CO VE& arg ) { auto BE = arg.BE() , EN = arg.EN(); auto itr = BE; WH( itr != EN ){ ( itr == BE ? os : os << " " ) << *itr; itr++; } RE os; } TE IN basic_ostream& VariadicCout( basic_ostream& os , CO Arg& arg ) { RE os << arg; } TE IN basic_ostream& VariadicCout( basic_ostream& os , CO Arg1& arg1 , CO Arg2& arg2 , CO ARGS&... args ) { RE VariadicCout( os << arg1 << " " , arg2 , args... ); } // データ構造用 TE TY V> IN V OP+( CO V& a0 , CO V& a1 ) { if( a0.empty() ){ RE a1; } if( a1.empty() ){ RE a0; } AS( a0.SZ() == a1.SZ() ); V answer{}; for( auto itr0 = a0.BE() , itr1 = a1.BE() , EN0 = a0.EN(); itr0 != EN0 ; itr0++ , itr1++ ){ answer.push_back( *itr0 + *itr1 ); } RE answer; } TE IN pair OP+( CO pair& t0 , CO pair& t1 ) { RE { t0.first + t1.first , t0.second + t1.second }; } TE IN tuple OP+( CO tuple& t0 , CO tuple& t1 ) { RE { get<0>( t0 ) + get<0>( t1 ) , get<1>( t0 ) + get<1>( t1 ) , get<2>( t0 ) + get<2>( t1 ) }; } TE IN tuple OP+( CO tuple& t0 , CO tuple& t1 ) { RE { get<0>( t0 ) + get<0>( t1 ) , get<1>( t0 ) + get<1>( t1 ) , get<2>( t0 ) + get<2>( t1 ) , get<3>( t0 ) + get<3>( t1 ) }; } // デバッグ用 #ifdef DEBUG IN VO AlertAbort( int n ) { CERR( "abort関数が呼ばれました。assertマクロのメッセージが出力されていない場合はオーバーフローの有無を確認をしてください。" ); } VO AutoCheck( int& exec_mode , CO bool& use_getline ); IN VO Solve(); IN VO Experiment(); IN VO SmallTest(); IN VO RandomTest(); ll GetRand( CRL Rand_min , CRL Rand_max ); IN VO BreakPoint( CRI LINE ) {} int exec_mode; CEXPR( int , solve_mode , 0 ); CEXPR( int , sample_debug_mode , 1 ); CEXPR( int , submission_debug_mode , 2 ); CEXPR( int , library_search_mode , 3 ); CEXPR( int , experiment_mode , 4 ); CEXPR( int , small_test_mode , 5 ); CEXPR( int , random_test_mode , 6 ); #ifdef USE_GETLINE CEXPR( bool , use_getline , true ); #else CEXPR( bool , use_getline , false ); #endif #else ll GetRand( CRL Rand_min , CRL Rand_max ) { ll answer = time( NULL ); RE answer * rand() % ( Rand_max + 1 - Rand_min ) + Rand_min; } #endif // VVV 常設ライブラリは以下に挿入する。 // Map // c:/Users/user/Documents/Programming/Mathematics/Function/Map/compress.txt CL is_ordered{PU:is_ordered()= delete;TE ST CE auto Check(CO T& t)-> decltype(t < t,true_type());ST CE false_type Check(...);TE ST CE CO bool value = is_same_v< decltype(Check(declval())),true_type >;}; TE US Map = conditional_t>,unordered_map,conditional_t,map,VO>>; // Algebra // c:/Users/user/Documents/Programming/Mathematics/Algebra/compress.txt #define DC_OF_CPOINT(POINT)IN CO U& POINT()CO NE #define DC_OF_POINT(POINT)IN U& POINT() NE #define DF_OF_CPOINT(POINT)TE IN CO U& VirtualPointedSet::POINT()CO NE{RE Point();} #define DF_OF_POINT(POINT)TE IN U& VirtualPointedSet::POINT()NE{RE Point();} TE CL UnderlyingSet{PU:US type = U;};TE CL VirtualPointedSet:virtual PU UnderlyingSet{PU:virtual CO U& Point()CO NE = 0;virtual U& Point() NE = 0;DC_OF_CPOINT(Unit);DC_OF_CPOINT(Zero);DC_OF_CPOINT(One);DC_OF_CPOINT(Infty);DC_OF_CPOINT(size);DC_OF_POINT(init);DC_OF_POINT(root);};TE CL PointedSet:virtual PU VirtualPointedSet{PU:U m_b_U;IN PointedSet(CO U& b_u = U());IN CO U& Point()CO NE;IN U& Point() NE;};TE CL VirtualNSet:virtual PU UnderlyingSet{PU:virtual U Transfer(CO U& u)= 0;IN U Inverse(CO U& u);};TE CL AbstractNSet:virtual PU VirtualNSet{PU:F_U& m_f_U;IN AbstractNSet(F_U& f_U);IN U Transfer(CO U& u);};TE CL VirtualMagma:virtual PU UnderlyingSet{PU:virtual U Product(CO U& u0,CO U& u1)= 0;IN U Sum(CO U& u0,CO U& u1);};TE CL AbstractMagma:virtual PU VirtualMagma{PU:M_U& m_m_U;IN AbstractMagma(M_U& m_U);IN U Product(CO U& u0,CO U& u1);}; TE IN PointedSet::PointedSet(CO U& b_U):m_b_U(b_U){}TE IN CO U& PointedSet::Point()CO NE{RE m_b_U;}TE IN U& PointedSet::Point()NE{RE m_b_U;}DF_OF_CPOINT(Unit);DF_OF_CPOINT(Zero);DF_OF_CPOINT(One);DF_OF_CPOINT(Infty);DF_OF_CPOINT(size);DF_OF_POINT(init);DF_OF_POINT(root);TE IN AbstractNSet::AbstractNSet(F_U& f_U):m_f_U(f_U){ST_AS(is_invocable_r_v);}TE IN U AbstractNSet::Transfer(CO U& u){RE m_f_U(u);}TE IN U VirtualNSet::Inverse(CO U& u){RE Transfer(u);}TE IN AbstractMagma::AbstractMagma(M_U& m_U):m_m_U(m_U){ST_AS(is_invocable_r_v);}TE IN U AbstractMagma::Product(CO U& u0,CO U& u1){RE m_m_U(u0,u1);}TE IN U VirtualMagma::Sum(CO U& u0,CO U& u1){RE Product(u0,u1);} TE CL VirtualMonoid:virtual PU VirtualMagma,virtual PU VirtualPointedSet{};TE CL AdditiveMonoid:virtual PU VirtualMonoid,PU PointedSet{PU:IN U Product(CO U& u0,CO U& u1);};TE CL MultiplicativeMonoid:virtual PU VirtualMonoid,PU PointedSet{PU:IN MultiplicativeMonoid(CO U& e_U);IN U Product(CO U& u0,CO U& u1);};TE CL AbstractMonoid:virtual PU VirtualMonoid,PU AbstractMagma,PU PointedSet{PU:IN AbstractMonoid(M_U& m_U,CO U& e_U);}; TE IN MultiplicativeMonoid::MultiplicativeMonoid(CO U& e_U):PointedSet(e_U){}TE IN AbstractMonoid::AbstractMonoid(M_U& m_U,CO U& e_U):AbstractMagma(m_U),PointedSet(e_U){}TE IN U AdditiveMonoid::Product(CO U& u0,CO U& u1){RE u0 + u1;}TE IN U MultiplicativeMonoid::Product(CO U& u0,CO U& u1){RE u0 * u1;} TE CL VirtualGroup:virtual PU VirtualMonoid,virtual PU VirtualPointedSet,virtual PU VirtualNSet{};TE CL AdditiveGroup:virtual PU VirtualGroup,PU AdditiveMonoid{PU:IN U Transfer(CO U& u);};TE CL AbstractGroup:virtual PU VirtualGroup,PU AbstractMonoid,PU AbstractNSet{PU:IN AbstractGroup(M_U& m_U,CO U& e_U,I_U& i_U);IN U Transfer(CO U& u);};TE IN AbstractGroup::AbstractGroup(M_U& m_U,CO U& e_U,I_U& i_U):AbstractMonoid(m_U,e_U),AbstractNSet(i_U){}TE IN U AbstractGroup::Transfer(CO U& u){RE m_i_U(u);}TE IN U AdditiveGroup::Transfer(CO U& u){RE -u;} TE CL VirtualRing{PU:GROUP m_R0;MONOID m_R1;IN VirtualRing(GROUP R0,MONOID R1);IN U Sum(CO U& u0,CO U& u1);IN CO U& Zero()CO NE;IN U Inverse(CO U& u);IN U Product(CO U& u0,CO U& u1);IN CO U& One()CO NE;IN GROUP& AdditiveGroup()NE;IN MONOID& MultiplicativeMonoid()NE;};TE CL Ring:virtual PU VirtualRing,MultiplicativeMonoid>{PU:IN Ring(CO U& one_U);};TE CL AbstractRing:virtual PU VirtualRing,AbstractMonoid>{PU:IN AbstractRing(A_U& a_U,CO U& z_U,I_U& i_U,M_U& m_U,CO U& e_U);}; TE IN VirtualRing::VirtualRing(GROUP R0,MONOID R1):m_R0(MO(R0)),m_R1(MO(R1)){}TE IN Ring::Ring(CO U& one_U):VirtualRing,MultiplicativeMonoid>(AdditiveGroup(),MultiplicativeMonoid(one_U)){}TE IN AbstractRing::AbstractRing(A_U& a_U,CO U& z_U,I_U& i_U,M_U& m_U,CO U& e_U):VirtualRing,AbstractMonoid>(AbstractGroup(a_U,z_U,i_U),AbstractMonoid(m_U,e_U)){}TE IN U VirtualRing::Sum(CO U& u0,CO U& u1){RE m_R0.Sum(u0,u1);}TE IN CO U& VirtualRing::Zero()CO NE{RE m_R0.Zero();}TE IN U VirtualRing::Inverse(CO U& u){RE m_R0.Inverse(u);}TE IN U VirtualRing::Product(CO U& u0,CO U& u1){RE m_R1.Product(u0,u1);}TE IN CO U& VirtualRing::One()CO NE{RE m_R1.One();}TE IN GROUP& VirtualRing::AdditiveGroup()NE{RE m_R0;}TE IN MONOID& VirtualRing::MultiplicativeMonoid()NE{RE m_R1;} // Graph // c:/Users/user/Documents/Programming/Mathematics/Geometry/Graph/compress.txt #define SFINAE_FOR_GRAPH TY T,TY E,enable_if_t,void*> PTR TE CL VirtualGraph:PU PointedSet{PU:E m_edge;IN VirtualGraph(CRI SZ,E edge);virtual R1 Enumeration(CRI i)= 0;virtual R2 Enumeration_inv(CO T& t)= 0;IN VO Reset();IN E& edge()NE;IN ret_t Edge(CO T& t);US type = T;};TE CL Graph:virtual PU VirtualGraph{PU:IN Graph(CRI SZ,E edge);IN CRI Enumeration(CRI i);IN CRI Enumeration_inv(CRI t);TE IN Graph GetGraph(F edge)CO;};TE CL EnumerationGraph:virtual PU VirtualGraph,ret_t,E>{PU:Enum_T& m_enum_T;Enum_T_inv& m_enum_T_inv;IN EnumerationGraph(CRI SZ,Enum_T& enum_T,Enum_T_inv& enum_T_inv,E edge);IN ret_t Enumeration(CRI i);IN ret_t Enumeration_inv(CO T& t);TE IN EnumerationGraph GetGraph(F edge)CO;};TE EnumerationGraph(CRI SZ,Enum_T& enum_T,Enum_T_inv& enum_T_inv,E edge)-> EnumerationGraph()(0)),Enum_T,Enum_T_inv,E>;TE CL MemorisationGraph:virtual PU VirtualGraph{PU:int m_LE;VE m_memory;Map m_memory_inv;IN MemorisationGraph(CRI SZ,E edge);IN T Enumeration(CRI i);IN CRI Enumeration_inv(CO T& t);IN VO Reset();TE IN MemorisationGraph GetGraph(F edge)CO;};TE MemorisationGraph(CRI SZ,E edge)-> MemorisationGraph()().back()),E>;TE MemorisationGraph(CRI SZ,E edge)-> MemorisationGraph(declval()().back())),E>; TE IN VirtualGraph::VirtualGraph(CRI SZ,E edge):PointedSet(SZ),m_edge(MO(edge)){ST_AS(is_COructible_v && is_COructible_v && is_invocable_v);}TE IN Graph::Graph(CRI SZ,E edge):VirtualGraph(SZ,MO(edge)){}TE IN EnumerationGraph::EnumerationGraph(CRI SZ,Enum_T& enum_T,Enum_T_inv& enum_T_inv,E edge):VirtualGraph,ret_t,E>(SZ,MO(edge)),m_enum_T(enum_T),m_enum_T_inv(enum_T_inv){}TE IN MemorisationGraph::MemorisationGraph(CRI SZ,E edge):VirtualGraph(SZ,MO(edge)),m_LE(),m_memory(),m_memory_inv(){}TE IN E& VirtualGraph::edge()NE{RE m_edge;}TE IN ret_t VirtualGraph::Edge(CO T& t){RE m_edge(t);}TE IN CRI Graph::Enumeration(CRI i){RE i;}TE IN ret_t EnumerationGraph::Enumeration(CRI i){RE m_enum_T(i);}TE IN T MemorisationGraph::Enumeration(CRI i){AS(0 <= i && i < m_LE);RE m_memory[i];}TE IN CRI Graph::Enumeration_inv(CRI i){RE i;}TE IN ret_t EnumerationGraph::Enumeration_inv(CO T& t){RE m_enum_T_inv(t);}TE IN CRI MemorisationGraph::Enumeration_inv(CO T& t){if(m_memory_inv.count(t)== 0){AS(m_LE < TH->SZ());m_memory.push_back(t);RE m_memory_inv[t]= m_LE++;}RE m_memory_inv[t];}TE VO VirtualGraph::Reset(){}TE IN VO MemorisationGraph::Reset(){m_LE = 0;m_memory.clear();m_memory_inv.clear();}TE TE IN Graph Graph::GetGraph(F edge)CO{RE Graph(TH->SZ(),MO(edge));}TE TE IN EnumerationGraph EnumerationGraph::GetGraph(F edge)CO{RE EnumerationGraph(TH->SZ(),m_enum_T,m_enum_T_inv,MO(edge));}TE TE IN MemorisationGraph MemorisationGraph::GetGraph(F edge)CO{RE MemorisationGraph(TH->SZ(),MO(edge));} // ConstexprModulo // c:/Users/user/Documents/Programming/Mathematics/Arithmetic/Mod/ConstexprModulo/compress.txt CEXPR(uint,P,998244353);TE CE INT& RS(INT& n)NE{RE n < 0?((((++n)*= -1)%= M)*= -1)+= M - 1:n %= M;}TE CE uint& RS(uint& n)NE{RE n %= M;}TE CE ull& RS(ull& n)NE{RE n %= M;}TE CE INT& RSP(INT& n)NE{CE CO uint trunc =(1 << 23)- 1;INT n_u = n >> 23;n &= trunc;INT n_uq =(n_u / 7)/ 17;n_u -= n_uq * 119;n += n_u << 23;RE n < n_uq?n += P - n_uq:n -= n_uq;}TE <> CE ull& RS(ull& n)NE{CE CO ull Pull = P;CE CO ull Pull2 =(Pull - 1)*(Pull - 1);RE RSP(n > Pull2?n -= Pull2:n);}TE CE INT RS(INT&& n)NE{RE MO(RS(n));}TE CE INT RS(CO INT& n)NE{RE RS(INT(n));} #define SFINAE_FOR_MOD(DEFAULT)TY T,enable_if_t>>* DEFAULT #define DC_OF_CM_FOR_MOD(FUNC)CE bool OP FUNC(CO Mod& n)CO NE #define DC_OF_AR_FOR_MOD(FUNC)CE Mod OP FUNC(CO Mod& n)CO NE;TE CE Mod OP FUNC(T&& n)CO NE; #define DF_OF_CM_FOR_MOD(FUNC)TE CE bool Mod::OP FUNC(CO Mod& n)CO NE{RE m_n FUNC n.m_n;} #define DF_OF_AR_FOR_MOD(FUNC,FORMULA)TE CE Mod Mod::OP FUNC(CO Mod& n)CO NE{RE MO(Mod(*TH)FUNC ## = n);}TE TE CE Mod Mod::OP FUNC(T&& n)CO NE{RE FORMULA;}TE CE Mod OP FUNC(T&& n0,CO Mod& n1)NE{RE MO(Mod(forward(n0))FUNC ## = n1);} TE CL Mod{PU:uint m_n;CE Mod()NE;CE Mod(CO Mod& n)NE;CE Mod(Mod& n)NE;CE Mod(Mod&& n)NE;TE CE Mod(CO T& n)NE;TE CE Mod(T& n)NE;TE CE Mod(T&& n)NE;CE Mod& OP=(CO Mod& n)NE;CE Mod& OP=(Mod&& n)NE;CE Mod& OP+=(CO Mod& n)NE;CE Mod& OP-=(CO Mod& n)NE;CE Mod& OP*=(CO Mod& n)NE;IN Mod& OP/=(CO Mod& n);CE Mod& OP<<=(int n)NE;CE Mod& OP>>=(int n)NE;CE Mod& OP++()NE;CE Mod OP++(int)NE;CE Mod& OP--()NE;CE Mod OP--(int)NE;DC_OF_CM_FOR_MOD(==);DC_OF_CM_FOR_MOD(!=);DC_OF_CM_FOR_MOD(<);DC_OF_CM_FOR_MOD(<=);DC_OF_CM_FOR_MOD(>);DC_OF_CM_FOR_MOD(>=);DC_OF_AR_FOR_MOD(+);DC_OF_AR_FOR_MOD(-);DC_OF_AR_FOR_MOD(*);DC_OF_AR_FOR_MOD(/);CE Mod OP<<(int n)CO NE;CE Mod OP>>(int n)CO NE;CE Mod OP-()CO NE;CE Mod& SignInvert()NE;CE Mod& Double()NE;CE Mod& Halve()NE;IN Mod& Invert();TE CE Mod& PositivePW(T&& EX)NE;TE CE Mod& NonNegativePW(T&& EX)NE;TE CE Mod& PW(T&& EX);CE VO swap(Mod& n)NE;CE CRUI RP()CO NE;ST CE Mod DeRP(CRUI n)NE;ST CE uint& Normalise(uint& n)NE;ST IN CO Mod& Inverse(CRUI n)NE;ST IN CO Mod& Factorial(CRUI n)NE;ST IN CO Mod& FactorialInverse(CRUI n)NE;ST IN Mod Combination(CRUI n,CRUI i)NE;ST IN CO Mod& zero()NE;ST IN CO Mod& one()NE;TE CE Mod& Ref(T&& n)NE;}; #define SFINAE_FOR_MN(DEFAULT)TY T,enable_if_t,decay_t>>* DEFAULT #define DC_OF_AR_FOR_MN(FUNC)IN MN OP FUNC(CO MN& n)CO NE;TE IN MN OP FUNC(T&& n)CO NE; #define DF_OF_CM_FOR_MN(FUNC)TE IN bool MN::OP FUNC(CO MN& n)CO NE{RE m_n FUNC n.m_n;} #define DF_OF_AR_FOR_MN(FUNC,FORMULA)TE IN MN MN::OP FUNC(CO MN& n)CO NE{RE MO(MN(*TH)FUNC ## = n);}TE TE IN MN MN::OP FUNC(T&& n)CO NE{RE FORMULA;}TE IN MN OP FUNC(T&& n0,CO MN& n1)NE{RE MO(MN(forward(n0))FUNC ## = n1);} TE CL MN:PU Mod{PU:CE MN()NE;CE MN(CO MN& n)NE;CE MN(MN& n)NE;CE MN(MN&& n)NE;TE CE MN(CO T& n)NE;TE CE MN(T&& n)NE;CE MN& OP=(CO MN& n)NE;CE MN& OP=(MN&& n)NE;CE MN& OP+=(CO MN& n)NE;CE MN& OP-=(CO MN& n)NE;CE MN& OP*=(CO MN& n)NE;IN MN& OP/=(CO MN& n);CE MN& OP<<=(int n)NE;CE MN& OP>>=(int n)NE;CE MN& OP++()NE;CE MN OP++(int)NE;CE MN& OP--()NE;CE MN OP--(int)NE;DC_OF_AR_FOR_MN(+);DC_OF_AR_FOR_MN(-);DC_OF_AR_FOR_MN(*);DC_OF_AR_FOR_MN(/);CE MN OP<<(int n)CO NE;CE MN OP>>(int n)CO NE;CE MN OP-()CO NE;CE MN& SignInvert()NE;CE MN& Double()NE;CE MN& Halve()NE;CE MN& Invert();TE CE MN& PositivePW(T&& EX)NE;TE CE MN& NonNegativePW(T&& EX)NE;TE CE MN& PW(T&& EX);CE uint RP()CO NE;CE Mod Reduce()CO NE;ST CE MN DeRP(CRUI n)NE;ST IN CO MN& Formise(CRUI n)NE;ST IN CO MN& Inverse(CRUI n)NE;ST IN CO MN& Factorial(CRUI n)NE;ST IN CO MN& FactorialInverse(CRUI n)NE;ST IN MN Combination(CRUI n,CRUI i)NE;ST IN CO MN& zero()NE;ST IN CO MN& one()NE;ST CE uint Form(CRUI n)NE;ST CE ull& Reduction(ull& n)NE;ST CE ull& ReducedMU(ull& n,CRUI m)NE;ST CE uint MU(CRUI n0,CRUI n1)NE;ST CE uint BaseSquareTruncation(uint& n)NE;TE CE MN& Ref(T&& n)NE;};TE CE MN Twice(CO MN& n)NE;TE CE MN Half(CO MN& n)NE;TE CE MN Inverse(CO MN& n);TE CE MN PW(MN n,T EX);TE CE MN<2> PW(CO MN<2>& n,CO T& p);TE CE T Square(CO T& t);TE <> CE MN<2> Square>(CO MN<2>& t);TE CE VO swap(MN& n0,MN& n1)NE;TE IN string to_string(CO MN& n)NE;TE IN basic_istream& OP>>(basic_istream& is,MN& n);TE IN basic_ostream& OP<<(basic_ostream& os,CO MN& n); TE CL COantsForMod{PU:COantsForMod()= delete;ST CE CO bool g_even =((M & 1)== 0);ST CE CO uint g_memory_bound = 1000000;ST CE CO uint g_memory_LE = M < g_memory_bound?M:g_memory_bound;ST CE ull MNBasePW(ull&& EX)NE;ST CE uint g_M_minus = M - 1;ST CE uint g_M_minus_2 = M - 2;ST CE uint g_M_minus_2_neg = 2 - M;ST CE CO int g_MN_digit = 32;ST CE CO ull g_MN_base = ull(1)<< g_MN_digit;ST CE CO uint g_MN_base_minus = uint(g_MN_base - 1);ST CE CO uint g_MN_digit_half =(g_MN_digit + 1)>> 1;ST CE CO uint g_MN_base_sqrt_minus =(1 << g_MN_digit_half)- 1;ST CE CO uint g_MN_M_neg_inverse = uint((g_MN_base - MNBasePW((ull(1)<<(g_MN_digit - 1))- 1))& g_MN_base_minus);ST CE CO uint g_MN_base_mod = uint(g_MN_base % M);ST CE CO uint g_MN_base_square_mod = uint(((g_MN_base % M)*(g_MN_base % M))% M);};TE CE ull COantsForMod::MNBasePW(ull&& EX)NE{ull prod = 1;ull PW = M;WH(EX != 0){(EX & 1)== 1?(prod *= PW)&= g_MN_base_minus:prod;EX >>= 1;(PW *= PW)&= g_MN_base_minus;}RE prod;} US MP = Mod

;US MNP = MN

;TE CE uint MN::Form(CRUI n)NE{ull n_copy = n;RE uint(MO(Reduction(n_copy *= COantsForMod::g_MN_base_square_mod)));}TE CE ull& MN::Reduction(ull& n)NE{ull n_sub = n & COantsForMod::g_MN_base_minus;RE((n +=((n_sub *= COantsForMod::g_MN_M_neg_inverse)&= COantsForMod::g_MN_base_minus)*= M)>>= COantsForMod::g_MN_digit)< M?n:n -= M;}TE CE ull& MN::ReducedMU(ull& n,CRUI m)NE{RE Reduction(n *= m);}TE CE uint MN::MU(CRUI n0,CRUI n1)NE{ull n0_copy = n0;RE uint(MO(ReducedMU(ReducedMU(n0_copy,n1),COantsForMod::g_MN_base_square_mod)));}TE CE uint MN::BaseSquareTruncation(uint& n)NE{CO uint n_u = n >> COantsForMod::g_MN_digit_half;n &= COantsForMod::g_MN_base_sqrt_minus;RE n_u;}TE CE MN::MN()NE:Mod(){ST_AS(! COantsForMod::g_even);}TE CE MN::MN(CO MN& n)NE:Mod(n){}TE CE MN::MN(MN& n)NE:Mod(n){}TE CE MN::MN(MN&& n)NE:Mod(MO(n)){}TE TE CE MN::MN(CO T& n)NE:Mod(n){ST_AS(! COantsForMod::g_even);Mod::m_n = Form(Mod::m_n);}TE TE CE MN::MN(T&& n)NE:Mod(forward(n)){ST_AS(! COantsForMod::g_even);Mod::m_n = Form(Mod::m_n);}TE CE MN& MN::OP=(CO MN& n)NE{RE Ref(Mod::OP=(n));}TE CE MN& MN::OP=(MN&& n)NE{RE Ref(Mod::OP=(MO(n)));}TE CE MN& MN::OP+=(CO MN& n)NE{RE Ref(Mod::OP+=(n));}TE CE MN& MN::OP-=(CO MN& n)NE{RE Ref(Mod::OP-=(n));}TE CE MN& MN::OP*=(CO MN& n)NE{ull m_n_copy = Mod::m_n;RE Ref(Mod::m_n = MO(ReducedMU(m_n_copy,n.m_n)));}TE IN MN& MN::OP/=(CO MN& n){RE OP*=(MN(n).Invert());}TE CE MN& MN::OP<<=(int n)NE{RE Ref(Mod::OP<<=(n));}TE CE MN& MN::OP>>=(int n)NE{RE Ref(Mod::OP>>=(n));}TE CE MN& MN::OP++()NE{RE Ref(Mod::Normalise(Mod::m_n += COantsForMod::g_MN_base_mod));}TE CE MN MN::OP++(int)NE{MN n{*TH};OP++();RE n;}TE CE MN& MN::OP--()NE{RE Ref(Mod::m_n < COantsForMod::g_MN_base_mod?((Mod::m_n += M)-= COantsForMod::g_MN_base_mod):Mod::m_n -= COantsForMod::g_MN_base_mod);}TE CE MN MN::OP--(int)NE{MN n{*TH};OP--();RE n;}DF_OF_AR_FOR_MN(+,MN(forward(n))+= *TH);DF_OF_AR_FOR_MN(-,MN(forward(n)).SignInvert()+= *TH);DF_OF_AR_FOR_MN(*,MN(forward(n))*= *TH);DF_OF_AR_FOR_MN(/,MN(forward(n)).Invert()*= *TH);TE CE MN MN::OP<<(int n)CO NE{RE MO(MN(*TH)<<= n);}TE CE MN MN::OP>>(int n)CO NE{RE MO(MN(*TH)>>= n);}TE CE MN MN::OP-()CO NE{RE MO(MN(*TH).SignInvert());}TE CE MN& MN::SignInvert()NE{RE Ref(Mod::m_n > 0?Mod::m_n = M - Mod::m_n:Mod::m_n);}TE CE MN& MN::Double()NE{RE Ref(Mod::Double());}TE CE MN& MN::Halve()NE{RE Ref(Mod::Halve());}TE CE MN& MN::Invert(){assert(Mod::m_n > 0);RE PositivePW(uint(COantsForMod::g_M_minus_2));}TE TE CE MN& MN::PositivePW(T&& EX)NE{MN PW{*TH};(--EX)%= COantsForMod::g_M_minus_2;WH(EX != 0){(EX & 1)== 1?OP*=(PW):*TH;EX >>= 1;PW *= PW;}RE *TH;}TE TE CE MN& MN::NonNegativePW(T&& EX)NE{RE EX == 0?Ref(Mod::m_n = COantsForMod::g_MN_base_mod):PositivePW(forward(EX));}TE TE CE MN& MN::PW(T&& EX){bool neg = EX < 0;assert(!(neg && Mod::m_n == 0));RE neg?PositivePW(forward(EX *= COantsForMod::g_M_minus_2_neg)):NonNegativePW(forward(EX));}TE CE uint MN::RP()CO NE{ull m_n_copy = Mod::m_n;RE MO(Reduction(m_n_copy));}TE CE Mod MN::Reduce()CO NE{ull m_n_copy = Mod::m_n;RE Mod::DeRP(MO(Reduction(m_n_copy)));}TE CE MN MN::DeRP(CRUI n)NE{RE MN(Mod::DeRP(n));}TE IN CO MN& MN::Formise(CRUI n)NE{ST MN memory[COantsForMod::g_memory_LE] ={zero(),one()};ST uint LE_curr = 2;WH(LE_curr <= n){memory[LE_curr] = DeRP(LE_curr);LE_curr++;}RE memory[n];}TE IN CO MN& MN::Inverse(CRUI n)NE{ST MN memory[COantsForMod::g_memory_LE] ={zero(),one()};ST uint LE_curr = 2;WH(LE_curr <= n){memory[LE_curr] = MN(Mod::Inverse(LE_curr));LE_curr++;}RE memory[n];}TE IN CO MN& MN::Factorial(CRUI n)NE{ST MN memory[COantsForMod::g_memory_LE] ={one(),one()};ST uint LE_curr = 2;ST MN val_curr{one()};ST MN val_last{one()};WH(LE_curr <= n){memory[LE_curr++] = val_curr *= ++val_last;}RE memory[n];}TE IN CO MN& MN::FactorialInverse(CRUI n)NE{ST MN memory[COantsForMod::g_memory_LE] ={one(),one()};ST uint LE_curr = 2;ST MN val_curr{one()};ST MN val_last{one()};WH(LE_curr <= n){memory[LE_curr] = val_curr *= Inverse(LE_curr);LE_curr++;}RE memory[n];}TE IN MN MN::Combination(CRUI n,CRUI i)NE{RE i <= n?Factorial(n)*FactorialInverse(i)*FactorialInverse(n - i):zero();}TE IN CO MN& MN::zero()NE{ST CE CO MN z{};RE z;}TE IN CO MN& MN::one()NE{ST CE CO MN o{DeRP(1)};RE o;}TE TE CE MN& MN::Ref(T&& n)NE{RE *TH;}TE CE MN Twice(CO MN& n)NE{RE MO(MN(n).Double());}TE CE MN Half(CO MN& n)NE{RE MO(MN(n).Halve());}TE CE MN Inverse(CO MN& n){RE MO(MN(n).Invert());}TE CE MN PW(MN n,T EX){RE MO(n.PW(EX));}TE CE VO swap(MN& n0,MN& n1)NE{n0.swap(n1);}TE IN string to_string(CO MN& n)NE{RE to_string(n.RP())+ " + MZ";}TE IN basic_istream& OP>>(basic_istream& is,MN& n){ll m;is >> m;n = m;RE is;}TE IN basic_ostream& OP<<(basic_ostream& os,CO MN& n){RE os << n.RP();} TE CE Mod::Mod()NE:m_n(){}TE CE Mod::Mod(CO Mod& n)NE:m_n(n.m_n){}TE CE Mod::Mod(Mod& n)NE:m_n(n.m_n){}TE CE Mod::Mod(Mod&& n)NE:m_n(MO(n.m_n)){}TE TE CE Mod::Mod(CO T& n)NE:m_n(RS(n)){}TE TE CE Mod::Mod(T& n)NE:m_n(RS(decay_t(n))){}TE TE CE Mod::Mod(T&& n)NE:m_n(RS(forward(n))){}TE CE Mod& Mod::OP=(CO Mod& n)NE{RE Ref(m_n = n.m_n);}TE CE Mod& Mod::OP=(Mod&& n)NE{RE Ref(m_n = MO(n.m_n));}TE CE Mod& Mod::OP+=(CO Mod& n)NE{RE Ref(Normalise(m_n += n.m_n));}TE CE Mod& Mod::OP-=(CO Mod& n)NE{RE Ref(m_n < n.m_n?(m_n += M)-= n.m_n:m_n -= n.m_n);}TE CE Mod& Mod::OP*=(CO Mod& n)NE{RE Ref(m_n = COantsForMod::g_even?RS(ull(m_n)* n.m_n):MN::MU(m_n,n.m_n));}TE <> CE MP& MP::OP*=(CO MP& n)NE{ull m_n_copy = m_n;RE Ref(m_n = MO((m_n_copy *= n.m_n)< P?m_n_copy:RSP(m_n_copy)));}TE IN Mod& Mod::OP/=(CO Mod& n){RE OP*=(Mod(n).Invert());}TE CE Mod& Mod::OP<<=(int n)NE{WH(n-- > 0){Normalise(m_n <<= 1);}RE *TH;}TE CE Mod& Mod::OP>>=(int n)NE{WH(n-- > 0){((m_n & 1)== 0?m_n:m_n += M)>>= 1;}RE *TH;}TE CE Mod& Mod::OP++()NE{RE Ref(m_n < COantsForMod::g_M_minus?++m_n:m_n = 0);}TE CE Mod Mod::OP++(int)NE{Mod n{*TH};OP++();RE n;}TE CE Mod& Mod::OP--()NE{RE Ref(m_n == 0?m_n = COantsForMod::g_M_minus:--m_n);}TE CE Mod Mod::OP--(int)NE{Mod n{*TH};OP--();RE n;}DF_OF_CM_FOR_MOD(==);DF_OF_CM_FOR_MOD(!=);DF_OF_CM_FOR_MOD(>);DF_OF_CM_FOR_MOD(>=);DF_OF_CM_FOR_MOD(<);DF_OF_CM_FOR_MOD(<=);DF_OF_AR_FOR_MOD(+,Mod(forward(n))+= *TH);DF_OF_AR_FOR_MOD(-,Mod(forward(n)).SignInvert()+= *TH);DF_OF_AR_FOR_MOD(*,Mod(forward(n))*= *TH);DF_OF_AR_FOR_MOD(/,Mod(forward(n)).Invert()*= *TH);TE CE Mod Mod::OP<<(int n)CO NE{RE MO(Mod(*TH)<<= n);}TE CE Mod Mod::OP>>(int n)CO NE{RE MO(Mod(*TH)>>= n);}TE CE Mod Mod::OP-()CO NE{RE MO(Mod(*TH).SignInvert());}TE CE Mod& Mod::SignInvert()NE{RE Ref(m_n > 0?m_n = M - m_n:m_n);}TE CE Mod& Mod::Double()NE{RE Ref(Normalise(m_n <<= 1));}TE CE Mod& Mod::Halve()NE{RE Ref(((m_n & 1)== 0?m_n:m_n += M)>>= 1);}TE IN Mod& Mod::Invert(){assert(m_n > 0);uint m_n_neg;RE m_n < COantsForMod::g_memory_LE?Ref(m_n = Inverse(m_n).m_n):((m_n_neg = M - m_n)< COantsForMod::g_memory_LE)?Ref(m_n = M - Inverse(m_n_neg).m_n):PositivePW(uint(COantsForMod::g_M_minus_2));}TE <> IN Mod<2>& Mod<2>::Invert(){assert(m_n > 0);RE *TH;}TE TE CE Mod& Mod::PositivePW(T&& EX)NE{Mod PW{*TH};EX--;WH(EX != 0){(EX & 1)== 1?OP*=(PW):*TH;EX >>= 1;PW *= PW;}RE *TH;}TE <> TE CE Mod<2>& Mod<2>::PositivePW(T&& EX)NE{RE *TH;}TE TE CE Mod& Mod::NonNegativePW(T&& EX)NE{RE EX == 0?Ref(m_n = 1):Ref(PositivePW(forward(EX)));}TE TE CE Mod& Mod::PW(T&& EX){bool neg = EX < 0;assert(!(neg && Mod::m_n == 0));RE neg?PositivePW(forward(EX *= COantsForMod::g_M_minus_2_neg)):NonNegativePW(forward(EX));}TE IN CO Mod& Mod::Inverse(CRUI n)NE{ST Mod memory[COantsForMod::g_memory_LE] ={zero(),one()};ST uint LE_curr = 2;WH(LE_curr <= n){memory[LE_curr].m_n = M - MN::MU(memory[M % LE_curr].m_n,M / LE_curr);LE_curr++;}RE memory[n];}TE IN CO Mod& Mod::Factorial(CRUI n)NE{ST Mod memory[COantsForMod::g_memory_LE] ={one(),one()};ST uint LE_curr = 2;WH(LE_curr <= n){memory[LE_curr] = MN::Factorial(LE_curr).Reduce();LE_curr++;}RE memory[n];}TE IN CO Mod& Mod::FactorialInverse(CRUI n)NE{ST Mod memory[COantsForMod::g_memory_LE] ={one(),one()};ST uint LE_curr = 2;WH(LE_curr <= n){memory[LE_curr] = MN::FactorialInverse(LE_curr).Reduce();LE_curr++;}RE memory[n];}TE IN Mod Mod::Combination(CRUI n,CRUI i)NE{RE MN::Combination(n,i).Reduce();}TE CE VO Mod::swap(Mod& n)NE{std::swap(m_n,n.m_n);}TE CE CRUI Mod::RP()CO NE{RE m_n;}TE CE Mod Mod::DeRP(CRUI n)NE{Mod n_copy{};n_copy.m_n = n;RE n_copy;}TE CE uint& Mod::Normalise(uint& n)NE{RE n < M?n:n -= M;}TE IN CO Mod& Mod::zero()NE{ST CE CO Mod z{};RE z;}TE IN CO Mod& Mod::one()NE{ST CE CO Mod o{DeRP(1)};RE o;}TE TE CE Mod& Mod::Ref(T&& n)NE{RE *TH;}TE CE Mod Twice(CO Mod& n)NE{RE MO(Mod(n).Double());}TE CE Mod Half(CO Mod& n)NE{RE MO(Mod(n).Halve());}TE IN Mod Inverse(CO Mod& n){RE MO(Mod(n).Invert());}TE CE Mod Inverse_COrexpr(CRUI n)NE{RE MO(Mod::DeRP(RS(n)).NonNegativePW(M - 2));}TE CE Mod PW(Mod n,T EX){RE MO(n.PW(EX));}TE CE Mod<2> PW(Mod<2> n,CO T& p){RE p == 0?Mod<2>::one():MO(n);}TE CE VO swap(Mod& n0,Mod& n1)NE{n0.swap(n1);}TE IN string to_string(CO Mod& n)NE{RE to_string(n.RP())+ " + MZ";}TE IN basic_istream& OP>>(basic_istream& is,Mod& n){ll m;is >> m;n = m;RE is;}TE IN basic_ostream& OP<<(basic_ostream& os,CO Mod& n){RE os << n.RP();} // AAA 常設ライブラリは以上に挿入する。 #define INCLUDE_LIBRARY #include __FILE__ #endif // INCLUDE_LIBRARY #endif // INCLUDE_SUB #endif // INCLUDE_MAIN