#line 1 "verify/graph/incremental_scc.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/incremental_scc"
#line 1 "graph/incremental_scc.hpp"
#include<algorithm>
#include<cassert>
#include<cstddef>
#include<utility>
#include<vector>#line 1 "graph/graph.hpp"
#include<array>
#line 8 "graph/graph.hpp"
namespacem1une{namespacegraph{template<classT=int>structEdge{usingcost_type=T;intfrom;intto;Tcost;intid;boolalive;Edge():from(-1),to(-1),cost(T()),id(-1),alive(true){}Edge(intfrom_,intto_,Tcost_=T(1),intid_=-1,boolalive_=true):from(from_),to(to_),cost(cost_),id(id_),alive(alive_){}intother(intv)const{assert(v==from||v==to);returnfrom^to^v;}};template<classT=int>structGraph{usingedge_type=Edge<T>;usingcost_type=T;private:structEdgePositions{std::array<std::pair<int,int>,2>value{};intsize=0;voidpush_back(std::pair<int,int>position){assert(size<2);value[size++]=position;}};int_n;int_edge_count;std::vector<std::vector<edge_type>>_g;std::vector<EdgePositions>_edge_positions;public:Graph():_n(0),_edge_count(0){}explicitGraph(intn):_n(n),_edge_count(0),_g(n){assert(0<=n);}intsize()const{return_n;}boolempty()const{return_n==0;}intedge_count()const{return_edge_count;}intadd_vertex(){_g.emplace_back();return_n++;}intadd_directed_edge(intfrom,intto,Tcost=T(1)){assert(0<=from&&from<_n);assert(0<=to&&to<_n);intid=_edge_count++;intidx=int(_g[from].size());_g[from].push_back(edge_type(from,to,cost,id));_edge_positions.emplace_back();_edge_positions.back().push_back({from,idx});returnid;}intadd_edge(intu,intv,Tcost=T(1)){assert(0<=u&&u<_n);assert(0<=v&&v<_n);intid=_edge_count++;intu_idx=int(_g[u].size());_g[u].push_back(edge_type(u,v,cost,id));intv_idx=int(_g[v].size());_g[v].push_back(edge_type(v,u,cost,id));_edge_positions.emplace_back();_edge_positions.back().push_back({u,u_idx});_edge_positions.back().push_back({v,v_idx});returnid;}voidset_edge_alive(intid,boolalive){assert(0<=id&&id<_edge_count);for(inti=0;i<_edge_positions[id].size;++i){auto[v,idx]=_edge_positions[id].value[i];_g[v][idx].alive=alive;}}voiderase_edge(intid){set_edge_alive(id,false);}voidrevive_edge(intid){set_edge_alive(id,true);}boolis_edge_alive(intid)const{assert(0<=id&&id<_edge_count);assert(_edge_positions[id].size!=0);auto[v,idx]=_edge_positions[id].value[0];return_g[v][idx].alive;}conststd::vector<edge_type>&operator[](intv)const{assert(0<=v&&v<_n);return_g[v];}std::vector<edge_type>&operator[](intv){assert(0<=v&&v<_n);return_g[v];}conststd::vector<std::vector<edge_type>>&adjacency()const{return_g;}std::vector<std::vector<edge_type>>&adjacency(){return_g;}std::vector<edge_type>edges(boolinclude_inactive=false)const{std::vector<edge_type>result;result.reserve(_edge_count);std::vector<char>used(_edge_count,false);for(intv=0;v<_n;v++){for(constauto&e:_g[v]){if(!include_inactive&&!e.alive)continue;if(0<=e.id&&e.id<_edge_count){if(used[e.id])continue;used[e.id]=true;}result.push_back(e);}}returnresult;}Graphreversed()const{Graphresult(_n);result._edge_count=_edge_count;result._edge_positions.assign(_edge_count,{});for(intv=0;v<_n;v++){for(constauto&e:_g[v]){intidx=int(result._g[e.to].size());result._g[e.to].push_back(edge_type(e.to,e.from,e.cost,e.id,e.alive));if(0<=e.id&&e.id<_edge_count)result._edge_positions[e.id].push_back({e.to,idx});}}returnresult;}};}// namespace graph}// namespace m1une#line 11 "graph/incremental_scc.hpp"
namespacem1une{namespacegraph{namespaceincremental_scc_detail{structEdgeEvent{intid;intfrom;intto;};inlinestd::vector<int>component_ids(intvertex_count,conststd::vector<EdgeEvent>&edges,inttime){std::vector<int>begin(vertex_count+1,0);std::vector<int>reverse_begin(vertex_count+1,0);intedge_count=0;for(constEdgeEvent&edge:edges){if(edge.id>=time)continue;begin[edge.from+1]++;reverse_begin[edge.to+1]++;edge_count++;}for(intvertex=0;vertex<vertex_count;vertex++){begin[vertex+1]+=begin[vertex];reverse_begin[vertex+1]+=reverse_begin[vertex];}std::vector<int>adjacency(edge_count);std::vector<int>reverse_adjacency(edge_count);std::vector<int>cursor=begin;std::vector<int>reverse_cursor=reverse_begin;for(constEdgeEvent&edge:edges){if(edge.id>=time)continue;adjacency[cursor[edge.from]++]=edge.to;reverse_adjacency[reverse_cursor[edge.to]++]=edge.from;}std::vector<int>().swap(cursor);std::vector<int>().swap(reverse_cursor);std::vector<char>visited(vertex_count,false);std::vector<int>next_position(begin.begin(),begin.end()-1);std::vector<int>order;order.reserve(vertex_count);std::vector<int>stack;for(intstart=0;start<vertex_count;start++){if(visited[start])continue;visited[start]=true;stack.push_back(start);while(!stack.empty()){constintvertex=stack.back();int&position=next_position[vertex];if(position<begin[vertex+1]){constintto=adjacency[position++];if(!visited[to]){visited[to]=true;stack.push_back(to);}}else{order.push_back(vertex);stack.pop_back();}}}std::vector<int>component(vertex_count,-1);intcomponent_count=0;for(autoiterator=order.rbegin();iterator!=order.rend();++iterator){constintstart=*iterator;if(component[start]!=-1)continue;component[start]=component_count;stack.push_back(start);while(!stack.empty()){constintvertex=stack.back();stack.pop_back();for(intposition=reverse_begin[vertex];position<reverse_begin[vertex+1];position++){constintto=reverse_adjacency[position];if(component[to]!=-1)continue;component[to]=component_count;stack.push_back(to);}}component_count++;}returncomponent;}}// namespace incremental_scc_detail// For every directed edge e, returns the first time t after e is inserted such// that its endpoints are in the same SCC. At time t, edges with IDs less than// t have been inserted. edge_count() + 1 means this never happens.template<classT>std::vector<int>incremental_scc(constGraph<T>&graph){usingincremental_scc_detail::EdgeEvent;usingincremental_scc_detail::component_ids;constintvertex_count=graph.size();constintedge_count=graph.edge_count();constintnever=edge_count+1;std::vector<int>merge_time(edge_count,never);if(edge_count==0)returnmerge_time;std::vector<EdgeEvent>edges_by_id(edge_count);std::vector<char>initialized(edge_count,false);for(intvertex=0;vertex<vertex_count;vertex++){for(constEdge<T>&edge:graph[vertex]){assert(0<=edge.id&&edge.id<edge_count);assert(!initialized[edge.id]);if(initialized[edge.id])continue;initialized[edge.id]=true;edges_by_id[edge.id]=EdgeEvent{edge.id,edge.from,edge.to};}}std::vector<EdgeEvent>events;events.reserve(edge_count);for(intedge_id=0;edge_id<edge_count;edge_id++){assert(initialized[edge_id]);if(graph.is_edge_alive(edge_id)){events.push_back(edges_by_id[edge_id]);}}std::vector<EdgeEvent>().swap(edges_by_id);std::vector<char>().swap(initialized);std::vector<int>new_index(vertex_count,-1);autodivide=[&](auto&&self,std::vector<EdgeEvent>current,intleft,intright)->void{if(current.empty()||right==left+1)return;constintmiddle=left+(right-left)/2;std::vector<int>touched;touched.reserve(std::min(std::size_t(vertex_count),current.size()*2));intcompressed_count=0;for(constEdgeEvent&edge:current){if(new_index[edge.from]==-1){new_index[edge.from]=compressed_count++;touched.push_back(edge.from);}if(new_index[edge.to]==-1){new_index[edge.to]=compressed_count++;touched.push_back(edge.to);}}for(EdgeEvent&edge:current){edge.from=new_index[edge.from];edge.to=new_index[edge.to];}for(intvertex:touched)new_index[vertex]=-1;std::vector<EdgeEvent>earlier;std::vector<EdgeEvent>later;earlier.reserve(current.size()/2);later.reserve(current.size()/2);{std::vector<int>component=component_ids(compressed_count,current,middle);for(constEdgeEvent&edge:current){constintfrom_component=component[edge.from];constintto_component=component[edge.to];if(edge.id<middle&&from_component==to_component){merge_time[edge.id]=std::min(merge_time[edge.id],middle);earlier.push_back(edge);}else{later.push_back(EdgeEvent{edge.id,from_component,to_component});}}}std::vector<EdgeEvent>().swap(current);self(self,std::move(earlier),left,middle);self(self,std::move(later),middle,right);};divide(divide,std::move(events),0,edge_count+1);returnmerge_time;}}// namespace graph}// namespace m1une#line 4 "verify/graph/incremental_scc.test.cpp"
#line 6 "verify/graph/incremental_scc.test.cpp"
#include<cstdint>
#line 9 "verify/graph/incremental_scc.test.cpp"
#line 1 "ds/dsu/dsu.hpp"
#line 5 "ds/dsu/dsu.hpp"
#include<numeric>
#line 8 "ds/dsu/dsu.hpp"
namespacem1une{namespaceds{structDsu{private:int_n;// parent_or_size[i] is the parent of i if it's >= 0.// If it's < 0, then i is a root and -parent_or_size[i] is the size of the group.std::vector<int>parent_or_size;// Returns {new leader, absorbed leader}. The absorbed leader is -1 when// both vertices already belong to the same component.std::pair<int,int>merge_leaders(inta,intb){intx=leader(a),y=leader(b);if(x==y)return{x,-1};if(-parent_or_size[x]<-parent_or_size[y])std::swap(x,y);parent_or_size[x]+=parent_or_size[y];parent_or_size[y]=x;return{x,y};}public:Dsu():_n(0){}explicitDsu(intn):_n(n),parent_or_size(n,-1){}// Merges the group containing 'a' with the group containing 'b'.// Returns the leader of the merged group.intmerge(inta,intb){returnmerge_leaders(a,b).first;}// Invokes callback(new_leader, absorbed_leader) after an actual merge.// Returns the leader of the merged group.template<classCallback>intmerge(inta,intb,Callback&&callback){std::pair<int,int>merged=merge_leaders(a,b);if(merged.second!=-1)callback(merged.first,merged.second);returnmerged.first;}// Returns true if 'a' and 'b' belong to the same group.boolsame(inta,intb){returnleader(a)==leader(b);}// Returns the leader (representative) of the group containing 'a'.intleader(inta){if(parent_or_size[a]<0)returna;// Path compressionreturnparent_or_size[a]=leader(parent_or_size[a]);}// Returns the size of the group containing 'a'.intsize(inta){return-parent_or_size[leader(a)];}// Returns a list of all groups, where each group is a vector of its elements.std::vector<std::vector<int>>groups(){std::vector<int>leader_buf(_n),group_size(_n);for(inti=0;i<_n;i++){leader_buf[i]=leader(i);group_size[leader_buf[i]]++;}std::vector<std::vector<int>>result(_n);for(inti=0;i<_n;i++){result[i].reserve(group_size[i]);}for(inti=0;i<_n;i++){result[leader_buf[i]].push_back(i);}result.erase(std::remove_if(result.begin(),result.end(),[&](conststd::vector<int>&v){returnv.empty();}),result.end());returnresult;}};}// namespace ds}// namespace m1une#line 1 "graph/scc.hpp"
#line 9 "graph/scc.hpp"
#line 11 "graph/scc.hpp"
namespacem1une{namespacegraph{structSccResult{intcount;std::vector<int>comp;std::vector<std::vector<int>>groups;boolsame(intu,intv)const{assert(0<=u&&u<int(comp.size()));assert(0<=v&&v<int(comp.size()));returncomp[u]==comp[v];}template<classT>Graph<int>dag(constGraph<T>&g)const{std::vector<std::pair<int,int>>edges;for(intv=0;v<g.size();v++){for(constauto&e:g[v]){if(!e.alive)continue;inta=comp[e.from],b=comp[e.to];if(a!=b)edges.emplace_back(a,b);}}std::sort(edges.begin(),edges.end());edges.erase(std::unique(edges.begin(),edges.end()),edges.end());Graph<int>result(count);for(auto[a,b]:edges)result.add_directed_edge(a,b);returnresult;}};template<classT>SccResultstrongly_connected_components(constGraph<T>&g){constintn=g.size();std::vector<std::vector<int>>reverse_graph(n);for(intvertex=0;vertex<n;vertex++){for(constauto&edge:g[vertex]){if(edge.alive)reverse_graph[edge.to].push_back(vertex);}}std::vector<char>seen(n,false);std::vector<int>order;order.reserve(n);std::vector<std::pair<int,std::size_t>>dfs_stack;for(intstart=0;start<n;start++){if(seen[start])continue;seen[start]=true;dfs_stack.emplace_back(start,0);while(!dfs_stack.empty()){intvertex=dfs_stack.back().first;std::size_t&edge_index=dfs_stack.back().second;while(edge_index<g[vertex].size()&&!g[vertex][edge_index].alive){edge_index++;}if(edge_index==g[vertex].size()){order.push_back(vertex);dfs_stack.pop_back();continue;}constintto=g[vertex][edge_index++].to;if(!seen[to]){seen[to]=true;dfs_stack.emplace_back(to,0);}}}std::vector<int>comp(n,-1);std::vector<std::vector<int>>groups;std::vector<int>stack;for(autoiterator=order.rbegin();iterator!=order.rend();++iterator){constintstart=*iterator;if(comp[start]!=-1)continue;constintcomponent=int(groups.size());groups.emplace_back();comp[start]=component;stack.push_back(start);while(!stack.empty()){constintvertex=stack.back();stack.pop_back();groups.back().push_back(vertex);for(intto:reverse_graph[vertex]){if(comp[to]!=-1)continue;comp[to]=component;stack.push_back(to);}}}returnSccResult{int(groups.size()),std::move(comp),std::move(groups)};}}// namespace graph}// namespace m1une#line 1 "math/modint.hpp"
#line 6 "math/modint.hpp"
#include<iostream>
#include<type_traits>
#line 9 "math/modint.hpp"
namespacem1une{namespacemath{template<uint32_tModulus>structModInt{static_assert(0<Modulus,"Modulus must be positive");private:uint32_t_v;public:staticconstexpruint32_tmod(){returnModulus;}staticconstexprModIntraw(uint32_tv)noexcept{ModIntx;x._v=v;returnx;}constexprModInt()noexcept:_v(0){}template<classInteger,std::enable_if_t<std::is_integral_v<Integer>,int>=0>constexprModInt(Integerv)noexcept{ifconstexpr(std::is_signed_v<Integer>){int64_tx=static_cast<int64_t>(v)%static_cast<int64_t>(Modulus);if(x<0)x+=Modulus;_v=static_cast<uint32_t>(x);}else{_v=static_cast<uint32_t>(static_cast<uint64_t>(v)%Modulus);}}constexpruint32_tval()constnoexcept{return_v;}constexprModInt&operator++()noexcept{_v++;if(_v==Modulus)_v=0;return*this;}constexprModInt&operator--()noexcept{if(_v==0)_v=Modulus;_v--;return*this;}constexprModIntoperator++(int)noexcept{ModIntres=*this;++*this;returnres;}constexprModIntoperator--(int)noexcept{ModIntres=*this;--*this;returnres;}constexprModInt&operator+=(constModInt&rhs)noexcept{_v+=rhs._v;if(_v>=Modulus)_v-=Modulus;return*this;}constexprModInt&operator-=(constModInt&rhs)noexcept{_v-=rhs._v;if(_v>=Modulus)_v+=Modulus;return*this;}constexprModInt&operator*=(constModInt&rhs)noexcept{uint64_tz=_v;z*=rhs._v;_v=static_cast<uint32_t>(z%Modulus);return*this;}constexprModInt&operator/=(constModInt&rhs)noexcept{return*this*=rhs.inv();}constexprModIntoperator+(constModInt&rhs)constnoexcept{returnModInt(*this)+=rhs;}constexprModIntoperator-(constModInt&rhs)constnoexcept{returnModInt(*this)-=rhs;}constexprModIntoperator*(constModInt&rhs)constnoexcept{returnModInt(*this)*=rhs;}constexprModIntoperator/(constModInt&rhs)constnoexcept{returnModInt(*this)/=rhs;}constexprbooloperator==(constModInt&rhs)constnoexcept{return_v==rhs._v;}constexprbooloperator!=(constModInt&rhs)constnoexcept{return_v!=rhs._v;}constexprModIntpow(longlongn)constnoexcept{ModIntres=raw(1%Modulus);ModIntx=n<0?inv():*this;uint64_texponent=n<0?uint64_t(-(n+1))+1:uint64_t(n);while(exponent>0){if(exponent&1)res*=x;x*=x;exponent>>=1;}returnres;}constexprModIntinv()constnoexcept{int64_ta=_v,b=Modulus,u=1,v=0;while(b){int64_tt=a/b;a-=t*b;std::swap(a,b);u-=t*v;std::swap(u,v);}assert(a==1);u%=Modulus;if(u<0)u+=Modulus;returnraw(static_cast<uint32_t>(u));}friendstd::ostream&operator<<(std::ostream&os,constModInt&rhs){returnos<<rhs._v;}friendstd::istream&operator>>(std::istream&is,ModInt&rhs){longlongv;is>>v;rhs=ModInt(v);returnis;}};usingmodint998244353=ModInt<998244353>;usingmodint1000000007=ModInt<1000000007>;template<intId=0>structDynamicModInt{private:uint32_t_v;inlinestaticuint32_t_mod=1;public:staticuint32_tmod()noexcept{return_mod;}staticvoidset_mod(uint32_tmodulus)noexcept{assert(modulus>0);assert(modulus<=uint32_t(1)<<31);_mod=modulus;}staticDynamicModIntraw(uint32_tv)noexcept{assert(v<_mod);DynamicModIntx;x._v=v;returnx;}DynamicModInt()noexcept:_v(0){}template<classInteger,std::enable_if_t<std::is_integral_v<Integer>,int>=0>DynamicModInt(Integerv)noexcept{ifconstexpr(std::is_signed_v<Integer>){int64_tx=static_cast<int64_t>(v)%static_cast<int64_t>(_mod);if(x<0)x+=_mod;_v=static_cast<uint32_t>(x);}else{_v=static_cast<uint32_t>(static_cast<uint64_t>(v)%_mod);}}uint32_tval()constnoexcept{return_v;}DynamicModInt&operator++()noexcept{_v++;if(_v==_mod)_v=0;return*this;}DynamicModInt&operator--()noexcept{if(_v==0)_v=_mod;_v--;return*this;}DynamicModIntoperator++(int)noexcept{DynamicModIntresult=*this;++*this;returnresult;}DynamicModIntoperator--(int)noexcept{DynamicModIntresult=*this;--*this;returnresult;}DynamicModInt&operator+=(constDynamicModInt&rhs)noexcept{_v+=rhs._v;if(_v>=_mod)_v-=_mod;return*this;}DynamicModInt&operator-=(constDynamicModInt&rhs)noexcept{_v-=rhs._v;if(_v>=_mod)_v+=_mod;return*this;}DynamicModInt&operator*=(constDynamicModInt&rhs)noexcept{_v=static_cast<uint32_t>(uint64_t(_v)*rhs._v%_mod);return*this;}DynamicModInt&operator/=(constDynamicModInt&rhs)noexcept{return*this*=rhs.inv();}DynamicModIntoperator+(constDynamicModInt&rhs)constnoexcept{returnDynamicModInt(*this)+=rhs;}DynamicModIntoperator-(constDynamicModInt&rhs)constnoexcept{returnDynamicModInt(*this)-=rhs;}DynamicModIntoperator*(constDynamicModInt&rhs)constnoexcept{returnDynamicModInt(*this)*=rhs;}DynamicModIntoperator/(constDynamicModInt&rhs)constnoexcept{returnDynamicModInt(*this)/=rhs;}booloperator==(constDynamicModInt&rhs)constnoexcept{return_v==rhs._v;}booloperator!=(constDynamicModInt&rhs)constnoexcept{return_v!=rhs._v;}DynamicModIntpow(longlongexponent)constnoexcept{DynamicModIntresult=raw(1%_mod);DynamicModIntbase=exponent<0?inv():*this;uint64_tmagnitude=exponent<0?uint64_t(-(exponent+1))+1:uint64_t(exponent);while(magnitude>0){if(magnitude&1)result*=base;base*=base;magnitude>>=1;}returnresult;}DynamicModIntinv()constnoexcept{int64_ta=_v,b=_mod,u=1,v=0;while(b){int64_tquotient=a/b;a-=quotient*b;std::swap(a,b);u-=quotient*v;std::swap(u,v);}assert(a==1);u%=_mod;if(u<0)u+=_mod;returnraw(static_cast<uint32_t>(u));}friendstd::ostream&operator<<(std::ostream&os,constDynamicModInt&rhs){returnos<<rhs._v;}friendstd::istream&operator>>(std::istream&is,DynamicModInt&rhs){longlongvalue;is>>value;rhs=DynamicModInt(value);returnis;}};}// namespace math}// namespace m1une#line 1 "utilities/fast_io.hpp"
#line 6 "utilities/fast_io.hpp"
#include<cerrno>
#include<charconv>
#line 9 "utilities/fast_io.hpp"
#include<cstdio>
#include<cstdlib>
#line 12 "utilities/fast_io.hpp"
#include<cstring>
#include<iterator>
#include<string>
#include<sys/stat.h>
#line 18 "utilities/fast_io.hpp"
#include<unistd.h>
#line 20 "utilities/fast_io.hpp"
namespacem1une{namespaceutilities{structFastOutput;namespaceinternal{// Shared with the convenience helpers in template.hpp.inlineFastOutput*standard_output_instance=nullptr;// Detect std::begin(x), std::end(x).template<classT,class=void>structis_range:std::false_type{};template<classT>structis_range<T,std::void_t<decltype(std::begin(std::declval<T&>())),decltype(std::end(std::declval<T&>()))>>:std::true_type{};template<classT>inlineconstexprboolis_range_v=is_range<T>::value;template<classT>usingrange_reference_t=decltype(*std::begin(std::declval<T&>()));template<classT>usingrange_value_t=std::remove_cv_t<std::remove_reference_t<range_reference_t<T>>>;template<classT,class=void>structrange_stored_value{usingtype=range_value_t<T>;};template<classT>structrange_stored_value<T,std::void_t<typenamestd::remove_cv_t<std::remove_reference_t<T>>::value_type>>{usingtype=typenamestd::remove_cv_t<std::remove_reference_t<T>>::value_type;};template<classT>usingrange_stored_value_t=typenamerange_stored_value<T>::type;// Treat strings and C strings as scalar output objects, not as ranges.template<classT>structis_char_array:std::false_type{};template<classT,std::size_tN>structis_char_array<T[N]>:std::bool_constant<std::is_same_v<std::remove_cv_t<T>,char>>{};template<classT>structis_string_like:std::bool_constant<std::is_same_v<std::decay_t<T>,std::string>||std::is_same_v<std::decay_t<T>,constchar*>||std::is_same_v<std::decay_t<T>,char*>||is_char_array<std::remove_reference_t<T>>::value>{};template<classT>inlineconstexprboolis_string_like_v=is_string_like<T>::value;// ModInt-like type: x.val() is printable, and x can be assigned from long long.template<classT,class=void>structhas_val_method:std::false_type{};template<classT>structhas_val_method<T,std::void_t<decltype(std::declval<constT&>().val())>>:std::true_type{};template<classT>inlineconstexprboolhas_val_method_v=has_val_method<T>::value;template<classT,class=void>structhas_static_mod_raw:std::false_type{};template<classT>structhas_static_mod_raw<T,std::void_t<decltype(T::mod()),decltype(T::raw(std::declval<uint32_t>()))>>:std::true_type{};template<classT>inlineconstexprboolhas_static_mod_raw_v=has_static_mod_raw<T>::value;// libstdc++ before GCC 16 does not classify __int128 as an integral type in// strict ISO modes such as -std=c++23. Keep the fast-I/O interface independent// of that implementation detail.template<classT>inlineconstexprboolis_integral_v=std::is_integral_v<T>||std::is_same_v<std::remove_cv_t<T>,__int128_t>||std::is_same_v<std::remove_cv_t<T>,__uint128_t>;template<classT>inlineconstexprboolis_signed_v=std::is_signed_v<T>||std::is_same_v<std::remove_cv_t<T>,__int128_t>;template<classT>structmake_unsigned{usingtype=std::make_unsigned_t<T>;};template<>structmake_unsigned<__int128_t>{usingtype=__uint128_t;};template<>structmake_unsigned<__uint128_t>{usingtype=__uint128_t;};template<classT>usingmake_unsigned_t=typenamemake_unsigned<std::remove_cv_t<T>>::type;}// namespace internalstructFastInput{staticconstexprintbuffer_size=1<<20;private:std::FILE*_stream;char_buffer[buffer_size];int_position;int_length;int_file_descriptor;bool_streaming;boolrefill(){_position=0;if(_streaming){ssize_tlength;do{length=::read(_file_descriptor,_buffer,buffer_size);}while(length<0&&errno==EINTR);if(length<=0){_length=0;returnfalse;}_length=int(length);}else{_length=int(std::fread(_buffer,1,buffer_size,_stream));}return_length!=0;}template<classT>boolread_integer_from_stream(T&value){if(!skip_spaces())returnfalse;intc=read_char_raw();boolnegative=false;if(c=='-'){negative=true;c=read_char_raw();}ifconstexpr(internal::is_signed_v<T>){Tresult=0;while('0'<=c&&c<='9'){result=negative?result*10-(c-'0'):result*10+(c-'0');c=read_char_raw();}value=result;}else{Tresult=0;while('0'<=c&&c<='9'){result=result*10+T(c-'0');c=read_char_raw();}value=negative?T(0)-result:result;}returntrue;}boolprepare_number(){if(_length-_position>=64)returntrue;constintremaining=_length-_position;if(remaining>0)std::memmove(_buffer,_buffer+_position,remaining);constintadded=int(std::fread(_buffer+remaining,1,buffer_size-remaining,_stream));_position=0;_length=remaining+added;if(_length<buffer_size)_buffer[_length]='\0';return_length!=0;}public:explicitFastInput(std::FILE*stream=stdin):_stream(stream),_position(0),_length(0),_file_descriptor(::fileno(stream)),_streaming([&]{structstatstatus;return_file_descriptor>=0&&::fstat(_file_descriptor,&status)==0&&!S_ISREG(status.st_mode);}()){}FastInput(constFastInput&)=delete;FastInput&operator=(constFastInput&)=delete;intread_char_raw(){if(_position==_length&&!refill())returnEOF;return_buffer[_position++];}boolskip_spaces(){intc=read_char_raw();while(c!=EOF&&c<=' ')c=read_char_raw();if(c==EOF)returnfalse;--_position;returntrue;}boolread(char&value){if(!skip_spaces())returnfalse;value=char(read_char_raw());returntrue;}boolread(std::string&value){if(!skip_spaces())returnfalse;value.clear();while(true){constintbegin=_position;while(_position<_length&&static_cast<unsignedchar>(_buffer[_position])>' '){++_position;}value.append(_buffer+begin,_position-begin);if(_position<_length){++_position;returntrue;}if(!refill())returntrue;}}boolread(bool&value){intx;if(!read(x))returnfalse;value=x!=0;returntrue;}template<classT>std::enable_if_t<internal::is_integral_v<T>&&!std::is_same_v<std::remove_cv_t<T>,bool>&&!std::is_same_v<std::remove_cv_t<T>,char>,bool>read(T&value){if(_streaming)returnread_integer_from_stream(value);if(!prepare_number())returnfalse;intc=static_cast<unsignedchar>(_buffer[_position++]);while(c<=' ')c=static_cast<unsignedchar>(_buffer[_position++]);boolnegative=false;if(c=='-'){negative=true;c=static_cast<unsignedchar>(_buffer[_position++]);}ifconstexpr(internal::is_signed_v<T>){Tresult=0;while('0'<=c&&c<='9'){constintfirst=c-'0';constintsecond=static_cast<unsignedchar>(_buffer[_position])-'0';if(0<=second&&second<=9){result=negative?result*100-(first*10+second):result*100+(first*10+second);++_position;}else{result=negative?result*10-first:result*10+first;}c=static_cast<unsignedchar>(_buffer[_position++]);}value=result;}else{Tresult=0;while('0'<=c&&c<='9'){constunsignedfirst=unsigned(c-'0');constintsecond=static_cast<unsignedchar>(_buffer[_position])-'0';if(0<=second&&second<=9){result=result*100+T(first*10+unsigned(second));++_position;}else{result=result*10+T(first);}c=static_cast<unsignedchar>(_buffer[_position++]);}value=negative?T(0)-result:result;}if(_position>_length)_position=_length;returntrue;}template<classT>std::enable_if_t<std::is_floating_point_v<T>,bool>read(T&value){if(!skip_spaces())returnfalse;intc=read_char_raw();boolnegative=false;if(c=='-'||c=='+'){negative=c=='-';c=read_char_raw();}longdoubleresult=0;while('0'<=c&&c<='9'){result=result*10+(c-'0');c=read_char_raw();}if(c=='.'){longdoubleplace=0.1L;c=read_char_raw();while('0'<=c&&c<='9'){result+=(c-'0')*place;place*=0.1L;c=read_char_raw();}}if(c=='e'||c=='E'){c=read_char_raw();boolexponent_negative=false;if(c=='-'||c=='+'){exponent_negative=c=='-';c=read_char_raw();}intexponent=0;while('0'<=c&&c<='9'){exponent=exponent*10+(c-'0');c=read_char_raw();}longdoublescale=1;longdoublepower=10;while(exponent>0){if(exponent&1)scale*=power;power*=power;exponent>>=1;}result=exponent_negative?result/scale:result*scale;}value=static_cast<T>(negative?-result:result);returntrue;}template<classT>std::enable_if_t<internal::has_val_method_v<T>&&!internal::is_integral_v<T>&&!internal::is_range_v<T>,bool>read(T&value){longlongx;if(!read(x))returnfalse;ifconstexpr(internal::has_static_mod_raw_v<T>){if(x>=0&&uint64_t(x)<uint64_t(T::mod())){value=T::raw(uint32_t(x));}else{value=T(x);}}else{value=T(x);}returntrue;}template<classFirst,classSecond>boolread(std::pair<First,Second>&value){if(!read(value.first))returnfalse;returnread(value.second);}template<classRange>std::enable_if_t<internal::is_range_v<Range>&&!internal::is_string_like_v<Range>,bool>read(Range&range){usingStoredValue=internal::range_stored_value_t<Range>;constexprboolnested=internal::is_range_v<StoredValue>&&!internal::is_string_like_v<StoredValue>;for(auto&&value:range){ifconstexpr(std::is_same_v<StoredValue,bool>&&!nested){boolx;if(!read(x))returnfalse;value=x;}else{if(!read(value))returnfalse;}}returntrue;}template<classFirst,classSecond,class...Rest>boolread(First&first,Second&second,Rest&...rest){if(!read(first))returnfalse;returnread(second,rest...);}template<classT>FastInput&operator>>(T&value){if(!read(value))std::abort();return*this;}};structFastOutput{staticconstexprintbuffer_size=1<<20;private:inlinestaticconstautodigit_quads=[]{std::array<char,40000>result{};for(inti=0;i<10000;i++){intvalue=i;for(intj=3;j>=0;j--){result[4*i+j]=char('0'+value%10);value/=10;}}returnresult;}();std::FILE*_stream;char_buffer[buffer_size];int_position;int_precision;std::chars_format_float_format;char_range_separator;std::string*_capture=nullptr;template<classT>std::stringformat_cell(constT&value){std::stringresult;structCaptureGuard{std::string*⌖std::string*previous;~CaptureGuard(){target=previous;}}guard{_capture,_capture};_capture=&result;write(value);returnresult;}template<classMatrix>voidwrite_aligned_matrix(constMatrix&matrix){std::vector<std::vector<std::string>>rows;std::vector<std::size_t>widths;for(constauto&row:matrix){auto&cells=rows.emplace_back();std::size_tcolumn=0;for(constauto&value:row){cells.push_back(format_cell(value));if(column==widths.size())widths.push_back(0);widths[column]=std::max(widths[column],cells.back().size());++column;}}boolfirst=true;for(constauto&row:rows){if(!first)write_char('\n');first=false;for(std::size_tcolumn=0;column<row.size();++column){if(column!=0)write_char(_range_separator);for(std::size_tpadding=row[column].size();padding<widths[column];++padding){write_char(' ');}write(row[column]);}}}public:explicitFastOutput(std::FILE*stream=stdout):_stream(stream),_position(0),_precision(6),_float_format(std::chars_format::general),_range_separator(' '){if(_stream==stdout&&internal::standard_output_instance==nullptr){internal::standard_output_instance=this;}}FastOutput(constFastOutput&)=delete;FastOutput&operator=(constFastOutput&)=delete;~FastOutput(){flush();if(internal::standard_output_instance==this){internal::standard_output_instance=nullptr;}}voidflush(){if(_position!=0){std::fwrite(_buffer,1,_position,_stream);_position=0;}std::fflush(_stream);}voidwrite_char(charc){if(_capture!=nullptr){_capture->push_back(c);return;}if(_position==buffer_size)flush();_buffer[_position++]=c;}voidwrite(constchar*s){while(*s!='\0')write_char(*s++);}voidwrite(conststd::string&s){if(_capture!=nullptr){_capture->append(s);return;}std::size_tposition=0;while(position<s.size()){if(_position==buffer_size)flush();conststd::size_tcopied=std::min<std::size_t>(buffer_size-_position,s.size()-position);std::memcpy(_buffer+_position,s.data()+position,copied);_position+=int(copied);position+=copied;}}voidwrite(charc){write_char(c);}voidwrite(boolvalue){write_char(value?'1':'0');}template<classT>std::enable_if_t<std::is_floating_point_v<T>>write(Tvalue){chardigits[128];auto[end,error]=std::to_chars(digits,digits+sizeof(digits),value,_float_format,_precision);if(error!=std::errc())std::abort();for(constchar*pointer=digits;pointer!=end;pointer++){write_char(*pointer);}}template<classT>std::enable_if_t<internal::is_integral_v<T>&&!std::is_same_v<std::remove_cv_t<T>,bool>&&!std::is_same_v<std::remove_cv_t<T>,char>>write(Tvalue){usingRaw=std::remove_cv_t<T>;usingUnsigned=internal::make_unsigned_t<Raw>;Unsignedmagnitude;ifconstexpr(internal::is_signed_v<Raw>){if(value<0){write_char('-');magnitude=Unsigned(0)-Unsigned(value);}else{magnitude=Unsigned(value);}}else{magnitude=value;}if(magnitude==0){write_char('0');return;}unsignedchunks[16];intcount=0;while(magnitude>=10000){constUnsignedquotient=magnitude/10000;chunks[count++]=unsigned(magnitude-quotient*10000);magnitude=quotient;}if(_capture==nullptr&&_position>buffer_size-64)flush();charcaptured[64];char*constbegin=_capture!=nullptr?captured:_buffer+_position;char*destination=begin;constunsignedleading=unsigned(magnitude);constchar*first=digit_quads.data()+4*leading;intskip=leading<10?3:leading<100?2:leading<1000?1:0;for(;skip<4;skip++)*destination++=first[skip];while(count--){constchar*digits=digit_quads.data()+4*chunks[count];std::memcpy(destination,digits,4);destination+=4;}if(_capture!=nullptr){_capture->append(begin,destination-begin);}else{_position+=int(destination-begin);}}template<classT>std::enable_if_t<internal::has_val_method_v<T>&&!internal::is_integral_v<T>&&!internal::is_range_v<T>>write(constT&value){write(value.val());}template<classFirst,classSecond>voidwrite(conststd::pair<First,Second>&value){write(value.first);write_char(' ');write(value.second);}template<classRange>std::enable_if_t<internal::is_range_v<Range>&&!internal::is_string_like_v<Range>>write(constRange&range){usingStoredValue=internal::range_stored_value_t<constRange>;constexprboolnested=internal::is_range_v<StoredValue>&&!internal::is_string_like_v<StoredValue>;boolfirst=true;for(constauto&value:range){if(!first)write_char(nested?'\n':_range_separator);first=false;ifconstexpr(std::is_same_v<StoredValue,bool>&&!nested){write(static_cast<bool>(value));}else{write(value);}}}template<classFirst,class...Rest>voidprint(constFirst&first,constRest&...rest){write(first);((write_char(' '),write(rest)),...);}voidprintln(){write_char('\n');}voidset_precision(intprecision){_precision=precision;}voidset_fixed(intprecision=6){_float_format=std::chars_format::fixed;_precision=precision;}voidset_general(intprecision=6){_float_format=std::chars_format::general;_precision=precision;}voidset_range_separator(charseparator){_range_separator=separator;}template<classMatrix>voidwrite_aligned(constMatrix&matrix){usingRow=internal::range_stored_value_t<constMatrix>;usingCell=internal::range_stored_value_t<constRow>;static_assert(internal::is_range_v<Row>&&!internal::is_string_like_v<Row>,"write_aligned requires a two-dimensional range");static_assert(!internal::is_range_v<Cell>||internal::is_string_like_v<Cell>,"write_aligned requires scalar cells");write_aligned_matrix(matrix);}template<classMatrix>voidprintln_aligned(constMatrix&matrix){write_aligned(matrix);write_char('\n');}template<class...Args>voidprintln(constArgs&...args){print(args...);write_char('\n');}template<classT>FastOutput&operator<<(constT&value){write(value);return*this;}};}// namespace utilities}// namespace m1une#line 14 "verify/graph/incremental_scc.test.cpp"
namespace{usingGraph=m1une::graph::Graph<>;voidvalidate(constGraph&graph,conststd::vector<std::pair<int,int>>&edges){constintn=graph.size();constintm=graph.edge_count();assert(int(edges.size())==m);conststd::vector<int>actual=m1une::graph::incremental_scc(graph);assert(int(actual.size())==m);std::vector<int>expected(m,m+1);m1une::ds::Dsureplay(n);for(inttime=1;time<=m;time++){Graphprefix(n);for(intedge_id=0;edge_id<time;edge_id++){if(!graph.is_edge_alive(edge_id))continue;prefix.add_directed_edge(edges[edge_id].first,edges[edge_id].second);}constautocomponents=m1une::graph::strongly_connected_components(prefix);for(intedge_id=0;edge_id<m;edge_id++){if(edge_id>=time||!graph.is_edge_alive(edge_id))continue;if(expected[edge_id]==m+1&&components.same(edges[edge_id].first,edges[edge_id].second)){expected[edge_id]=time;}if(actual[edge_id]==time){replay.merge(edges[edge_id].first,edges[edge_id].second);}}for(intfirst=0;first<n;first++){for(intsecond=0;second<n;second++){assert(replay.same(first,second)==components.same(first,second));}}}assert(actual==expected);}voidtest_fixed(){Graphempty(3);validate(empty,std::vector<std::pair<int,int>>());Graphgraph(4);std::vector<std::pair<int,int>>edges;edges.emplace_back(0,1);graph.add_directed_edge(0,1);edges.emplace_back(1,2);graph.add_directed_edge(1,2);edges.emplace_back(2,0);graph.add_directed_edge(2,0);edges.emplace_back(2,3);graph.add_directed_edge(2,3);edges.emplace_back(3,3);graph.add_directed_edge(3,3);validate(graph,edges);conststd::vector<int>time=m1une::graph::incremental_scc(graph);assert(time[0]==3);assert(time[1]==3);assert(time[2]==3);assert(time[3]==6);assert(time[4]==5);graph.erase_edge(2);validate(graph,edges);}voidtest_randomized(){std::uint64_tstate=20260718;autorandom=[&state](){state^=state<<7;state^=state>>9;returnstate;};for(inttrial=0;trial<500;trial++){constintn=1+int(random()%8);constintm=int(random()%17);Graphgraph(n);std::vector<std::pair<int,int>>edges;edges.reserve(m);for(intedge_id=0;edge_id<m;edge_id++){constintfrom=int(random()%n);constintto=int(random()%n);edges.emplace_back(from,to);constintid=graph.add_directed_edge(from,to);if(random()%7==0)graph.erase_edge(id);}validate(graph,edges);}}}// namespaceintmain(){test_fixed();test_randomized();usingMint=m1une::math::modint998244353;m1une::utilities::FastInputfast_input;m1une::utilities::FastOutputfast_output;intvertex_count,edge_count;fast_input>>vertex_count>>edge_count;std::vector<Mint>weight(vertex_count);for(Mint&value:weight){intinput;fast_input>>input;value=Mint(input);}Graphgraph(vertex_count);std::vector<std::pair<int,int>>edges;edges.reserve(edge_count);for(intedge_id=0;edge_id<edge_count;edge_id++){intfrom,to;fast_input>>from>>to;edges.emplace_back(from,to);graph.add_directed_edge(from,to);}conststd::vector<int>merge_time=m1une::graph::incremental_scc(graph);std::vector<std::vector<int>>edges_by_time(edge_count+1);for(intedge_id=0;edge_id<edge_count;edge_id++){if(merge_time[edge_id]<=edge_count){edges_by_time[merge_time[edge_id]].push_back(edge_id);}}m1une::ds::Dsucomponents(vertex_count);Mintanswer=0;for(inttime=1;time<=edge_count;time++){for(intedge_id:edges_by_time[time]){constintfirst=components.leader(edges[edge_id].first);constintsecond=components.leader(edges[edge_id].second);if(first==second)continue;answer+=weight[first]*weight[second];components.merge(first,second,[&](intleader,intabsorbed){weight[leader]+=weight[absorbed];});}fast_output<<answer.val()<<'\n';}}