#define PROBLEM "https://judge.yosupo.jp/problem/general_matching"
#include"../../utilities/fast_io.hpp"#include<bits/stdc++.h>usingnamespacestd;#include"../../graph/graph.hpp"
#include"../../graph/general_matching.hpp"intmain(){m1une::utilities::FastInputfast_input;m1une::utilities::FastOutputfast_output;intN,M;fast_input>>N>>M;m1une::graph::GeneralMatchinggm(N);while(M--){intu,v;fast_input>>u>>v;gm.add_edge(u,v);}fast_output<<gm.max_matching()<<'\n';for(autop:gm.matching()){fast_output<<p.from<<' '<<p.to<<'\n';}}
#line 1 "verify/graph/library_checker_general_matching.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/general_matching"
#line 1 "utilities/fast_io.hpp"
#include<algorithm>
#include<array>
#include<cerrno>
#include<charconv>
#include<cstddef>
#include<cstdio>
#include<cstdlib>
#include<cstdint>
#include<cstring>
#include<iterator>
#include<string>
#include<sys/stat.h>
#include<type_traits>
#include<utility>
#include<unistd.h>
#include<vector>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 4 "verify/graph/library_checker_general_matching.test.cpp"
#include<bits/stdc++.h>usingnamespacestd;#line 1 "graph/graph.hpp"
#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 1 "graph/general_matching.hpp"
#line 6 "graph/general_matching.hpp"
#include<optional>
#line 9 "graph/general_matching.hpp"
#line 11 "graph/general_matching.hpp"
namespacem1une{namespacegraph{structGeneralMatching{structEdge{intfrom;intto;intid;boolalive;intother(intv)const{assert(v==from||v==to);returnfrom^to^v;}};structPair{intfrom;intto;intedge_id;};private:int_n;std::vector<Edge>_edges;std::vector<std::vector<int>>_adj;std::vector<int>_mate;std::vector<int>_mate_edge;bool_calculated;voidinvalidate(){_calculated=false;}voidensure_matching(){if(!_calculated)max_matching();}boolis_matched_edge(intid)const{constauto&e=_edges[id];return_mate[e.from]==e.to&&_mate_edge[e.from]==id;}enumMatchingLabel:char{even_label,odd_label,unlabeled};structMutablePartition{std::vector<int>parent;std::vector<int>rank;std::vector<int>representative;MutablePartition()=default;explicitMutablePartition(intn){reset(n);}voidreset(intn){parent.resize(n);rank.assign(n,0);representative.resize(n);for(inti=0;i<n;i++){parent[i]=i;representative[i]=i;}}introot(intv){if(parent[v]==v)returnv;returnparent[v]=root(parent[v]);}intoperator()(intv){returnrepresentative[root(v)];}voidunite(inta,intb){intra=root(a);intrb=root(b);if(ra==rb)return;if(rank[ra]<rank[rb])std::swap(ra,rb);parent[rb]=ra;if(rank[ra]==rank[rb])rank[ra]++;}voidmake_rep(intv){representative[root(v)]=v;}};structEdgeBucketQueue{std::vector<std::vector<int>>bucket;std::vector<int>head;voidreset(intn){bucket.assign(n+3,{});head.assign(n+3,0);}voidinsert(intedge_id,intkey){if(key<0||int(bucket.size())<=key)return;bucket[key].push_back(edge_id);}intpop(intkey){if(key<0||int(bucket.size())<=key)return-1;if(head[key]==int(bucket[key].size()))return-1;returnbucket[key][head[key]++];}};structNewMatchingPair{intfrom;intto;intedge_id;};// General-graph shortest augmenting path phase solver.structMicaliVaziraniSolver{GeneralMatching&graph;intn;intmatching_size;intdelta;intvisit_token;inteven_time_token;MutablePartitionbase;MutablePartitiondelayed_base;EdgeBucketQueuequeue;std::vector<MatchingLabel>label;std::vector<MatchingLabel>h_label;std::vector<int>parent;std::vector<int>parent_edge;std::vector<int>source_bridge;std::vector<int>target_bridge;std::vector<int>bridge_edge;std::vector<int>lcp;std::vector<int>path_mark_1;std::vector<int>path_mark_2;std::vector<int>restore_vertex;std::vector<int>restore_value;std::vector<int>rep;std::vector<int>h_mate;std::vector<char>is_h_edge;std::vector<std::vector<int>>contracted_into;std::vector<int>h_parent_edge;std::vector<int>h_even_time;std::vector<int>h_bridge_edge;std::vector<int>h_bridge_dir;explicitMicaliVaziraniSolver(GeneralMatching&graph_):graph(graph_),n(graph_._n),matching_size(0),delta(0),visit_token(0),even_time_token(0),base(n),delayed_base(n),label(n,unlabeled),h_label(n,unlabeled),parent(n,-1),parent_edge(n,-1),source_bridge(n,-1),target_bridge(n,-1),bridge_edge(n,-1),lcp(n,0),path_mark_1(n,0),path_mark_2(n,0),rep(n,-1),h_mate(n,-1),is_h_edge(graph_._edges.size(),false),contracted_into(n),h_parent_edge(n,-1),h_even_time(n,0),h_bridge_edge(n,-1),h_bridge_dir(n,0){}boolactive(intedge_id)const{returngraph._edges[edge_id].alive;}intother(intedge_id,intv)const{returngraph._edges[edge_id].other(v);}intedge_weight(intedge_id)const{returngraph.is_matched_edge(edge_id)?2:0;}voidset_match(intedge_id){constauto&e=graph._edges[edge_id];graph._mate[e.from]=e.to;graph._mate[e.to]=e.from;graph._mate_edge[e.from]=edge_id;graph._mate_edge[e.to]=edge_id;}voidinitialize_greedy_matching(){graph._mate.assign(n,-1);graph._mate_edge.assign(n,-1);matching_size=0;for(constauto&e:graph._edges){if(!e.alive)continue;if(graph._mate[e.from]!=-1||graph._mate[e.to]!=-1)continue;set_match(e.id);matching_size++;}}voidscan_edge(intedge_id,intfrom){if(!active(edge_id))return;intto=other(edge_id,from);if(to==from||graph._mate[to]==from||label[base(to)]==odd_label)return;if(label[to]==unlabeled){queue.insert(edge_id,lcp[from]+2);}else{queue.insert(edge_id,(lcp[from]+lcp[to])/2+1);}}voidshrink_path(intblossom_base,intx,inty,intedge_id,std::vector<std::pair<int,int>>&delayed_unions){intv=base(x);while(v!=blossom_base){base.unite(v,blossom_base);delayed_unions.push_back({v,blossom_base});v=graph._mate[v];assert(v!=-1);base.unite(v,blossom_base);delayed_unions.push_back({v,blossom_base});base.make_rep(blossom_base);source_bridge[v]=x;target_bridge[v]=y;bridge_edge[v]=edge_id;restore_vertex.push_back(v);restore_value.push_back(lcp[v]);lcp[v]=lcp[x]+lcp[y]-lcp[graph._mate[v]]+2;for(intid:graph._adj[v])scan_edge(id,v);assert(parent[v]!=-1);v=base(parent[v]);}delayed_unions.push_back({blossom_base,blossom_base});}voidbuild_phase_graph(){std::fill(h_mate.begin(),h_mate.end(),-1);std::fill(is_h_edge.begin(),is_h_edge.end(),false);for(auto&vertices:contracted_into)vertices.clear();for(intv=0;v<n;v++)contracted_into[delayed_base(v)].push_back(v);for(constauto&e:graph._edges){if(!e.alive)continue;intu=e.from;intv=e.to;intuh=delayed_base(u);intvh=delayed_base(v);if(uh==vh)continue;if(label[uh]==odd_label&&label[vh]==odd_label)continue;intw=edge_weight(e.id);booleven_odd=(label[uh]==even_label&&label[vh]==odd_label&&lcp[v]==lcp[u]+1-w)||(label[vh]==even_label&&label[uh]==odd_label&&lcp[u]==lcp[v]+1-w);boolunlabeled_unlabeled=label[uh]==unlabeled&&label[vh]==unlabeled&&w==2;booleven_unlabeled=(label[uh]==even_label&&label[vh]==unlabeled&&lcp[u]==delta-2)||(label[vh]==even_label&&label[uh]==unlabeled&&lcp[v]==delta-2);booleven_even=label[uh]==even_label&&label[vh]==even_label;booltight_even_even=even_even&&lcp[u]+lcp[v]==2*delta+w-2;if(even_odd||unlabeled_unlabeled||even_unlabeled||tight_even_even){is_h_edge[e.id]=true;if(w==2){h_mate[uh]=vh;h_mate[vh]=uh;}}}}boolphase_one(){delta=0;base.reset(n);delayed_base.reset(n);queue.reset(n);std::fill(label.begin(),label.end(),unlabeled);std::fill(parent.begin(),parent.end(),-1);std::fill(parent_edge.begin(),parent_edge.end(),-1);std::fill(source_bridge.begin(),source_bridge.end(),-1);std::fill(target_bridge.begin(),target_bridge.end(),-1);std::fill(bridge_edge.begin(),bridge_edge.end(),-1);std::fill(lcp.begin(),lcp.end(),0);for(intv=0;v<n;v++){if(graph._mate[v]==-1)label[v]=even_label;}for(intv=0;v<n;v++){if(label[v]!=even_label)continue;for(intid:graph._adj[v])scan_edge(id,v);}std::vector<std::pair<int,int>>delayed_unions;while(delta<=n+1){restore_vertex.clear();restore_value.clear();while(true){intedge_id=queue.pop(delta);if(edge_id==-1)break;if(!active(edge_id))continue;intx=graph._edges[edge_id].from;inty=graph._edges[edge_id].to;if(label[base(x)]!=even_label)std::swap(x,y);if(label[base(x)]!=even_label)continue;if(graph._mate[x]==y||base(x)==base(y)||label[base(y)]==odd_label)continue;if(label[base(y)]==unlabeled){intz=graph._mate[y];assert(z!=-1);lcp[y]=lcp[x]+1;lcp[z]=lcp[x]+2;parent[y]=x;parent_edge[y]=edge_id;parent[z]=y;parent_edge[z]=graph._mate_edge[z];label[y]=odd_label;label[z]=even_label;for(intid:graph._adj[z])scan_edge(id,z);continue;}if(label[base(y)]!=even_label||lcp[x]+lcp[y]!=2*delta-2)continue;++visit_token;inthx=base(x);inthy=base(y);path_mark_1[hx]=visit_token;path_mark_2[hy]=visit_token;while(path_mark_1[hy]!=visit_token&&path_mark_2[hx]!=visit_token&&(graph._mate[hx]!=-1||graph._mate[hy]!=-1)){if(graph._mate[hx]!=-1){assert(parent[graph._mate[hx]]!=-1);hx=base(parent[graph._mate[hx]]);path_mark_1[hx]=visit_token;}if(graph._mate[hy]!=-1){assert(parent[graph._mate[hy]]!=-1);hy=base(parent[graph._mate[hy]]);path_mark_2[hy]=visit_token;}}if(path_mark_1[hy]==visit_token||path_mark_2[hx]==visit_token){intblossom_base=path_mark_1[hy]==visit_token?hy:hx;shrink_path(blossom_base,x,y,edge_id,delayed_unions);shrink_path(blossom_base,y,x,edge_id,delayed_unions);}else{for(inti=int(restore_vertex.size())-1;i>=0;i--){lcp[restore_vertex[i]]=restore_value[i];}build_phase_graph();returntrue;}}for(auto[a,b]:delayed_unions){if(a==b){delayed_base.make_rep(a);}else{delayed_base.unite(a,b);}}delayed_unions.clear();delta++;}returnfalse;}intnext_h_vertex_through_edge(intedge_id,intcurrent_h)const{constauto&e=graph._edges[edge_id];returnrep[rep[e.from]==current_h?e.to:e.from];}intfind_path_in_h(inth_vertex){for(intv:contracted_into[h_vertex]){for(intedge_id:graph._adj[v]){if(!is_h_edge[edge_id])continue;intuh=rep[other(edge_id,v)];if(h_mate[h_vertex]==uh)continue;if(h_label[uh]==unlabeled){intmate_uh=h_mate[uh];h_label[uh]=odd_label;h_parent_edge[uh]=edge_id;if(mate_uh==-1)returnuh;h_label[mate_uh]=even_label;h_even_time[mate_uh]=even_time_token++;intfound=find_path_in_h(mate_uh);if(found!=-1)returnfound;}else{intbh=delayed_base(h_vertex);intzh=delayed_base(uh);if(h_even_time[bh]>=h_even_time[zh])continue;std::vector<int>blossom_path;std::vector<int>blossom_vertices;while(zh!=bh){blossom_vertices.push_back(zh);zh=h_mate[zh];assert(zh!=-1);blossom_vertices.push_back(zh);blossom_path.push_back(zh);assert(h_parent_edge[zh]!=-1);zh=delayed_base(next_h_vertex_through_edge(h_parent_edge[zh],zh));}for(intx:blossom_vertices)delayed_base.unite(x,bh);delayed_base.make_rep(bh);std::reverse(blossom_path.begin(),blossom_path.end());for(intx:blossom_path){h_bridge_edge[x]=edge_id;h_bridge_dir[x]=graph._edges[edge_id].to==v?1:-1;}for(intx:blossom_path){intfound=find_path_in_h(x);if(found!=-1)returnfound;}}}}return-1;}voidcollect_path_in_h(std::vector<int>&path,intfrom_h,intto_h){if(from_h==to_h)return;if(h_label[from_h]==even_label){intmate_from=h_mate[from_h];assert(mate_from!=-1);intedge_id=h_parent_edge[mate_from];assert(edge_id!=-1);path.push_back(edge_id);collect_path_in_h(path,next_h_vertex_through_edge(edge_id,mate_from),to_h);}else{intedge_id=h_bridge_edge[from_h];assert(edge_id!=-1);constauto&e=graph._edges[edge_id];intfirst=rep[h_bridge_dir[from_h]==1?e.from:e.to];intsecond=rep[h_bridge_dir[from_h]==1?e.to:e.from];collect_path_in_h(path,first,rep[h_mate[from_h]]);path.push_back(edge_id);collect_path_in_h(path,second,to_h);}}voidadd_new_pair(std::vector<NewMatchingPair>&pairs,intfrom,intto,intedge_id)const{constauto&e=graph._edges[edge_id];assert(e.alive);assert((e.from==from&&e.to==to)||(e.from==to&&e.to==from));pairs.push_back(NewMatchingPair{from,to,edge_id});}voidcollect_path_in_graph(std::vector<NewMatchingPair>&pairs,intfrom,intto){if(from==to)return;if(label[from]==even_label){intmate_from=graph._mate[from];assert(mate_from!=-1);intparent_of_mate=parent[mate_from];intedge_id=parent_edge[mate_from];assert(parent_of_mate!=-1&&edge_id!=-1);add_new_pair(pairs,mate_from,parent_of_mate,edge_id);collect_path_in_graph(pairs,parent_of_mate,to);}else{assert(source_bridge[from]!=-1&&target_bridge[from]!=-1&&bridge_edge[from]!=-1);collect_path_in_graph(pairs,source_bridge[from],graph._mate[from]);add_new_pair(pairs,source_bridge[from],target_bridge[from],bridge_edge[from]);collect_path_in_graph(pairs,target_bridge[from],to);}}voidaugment_path(conststd::vector<int>&h_path){std::vector<NewMatchingPair>pairs;for(intedge_id:h_path){constauto&e=graph._edges[edge_id];add_new_pair(pairs,e.from,e.to,edge_id);collect_path_in_graph(pairs,e.from,rep[e.from]);collect_path_in_graph(pairs,e.to,rep[e.to]);}for(constauto&p:pairs){if(graph._mate[p.from]!=-1){intold=graph._mate[p.from];graph._mate[old]=-1;graph._mate_edge[old]=-1;}if(graph._mate[p.to]!=-1){intold=graph._mate[p.to];graph._mate[old]=-1;graph._mate_edge[old]=-1;}graph._mate[p.from]=graph._mate[p.to]=-1;graph._mate_edge[p.from]=graph._mate_edge[p.to]=-1;}for(constauto&p:pairs){assert(graph._mate[p.from]==-1&&graph._mate[p.to]==-1);graph._mate[p.from]=p.to;graph._mate[p.to]=p.from;graph._mate_edge[p.from]=p.edge_id;graph._mate_edge[p.to]=p.edge_id;}matching_size++;}voidphase_two(){std::fill(h_label.begin(),h_label.end(),unlabeled);std::fill(h_parent_edge.begin(),h_parent_edge.end(),-1);std::fill(h_bridge_edge.begin(),h_bridge_edge.end(),-1);std::fill(h_bridge_dir.begin(),h_bridge_dir.end(),0);for(intv=0;v<n;v++)rep[v]=delayed_base(v);std::vector<std::vector<int>>paths;for(inth_vertex=0;h_vertex<n;h_vertex++){if(rep[h_vertex]!=h_vertex)continue;if(h_label[h_vertex]!=unlabeled||h_mate[h_vertex]!=-1)continue;h_label[h_vertex]=even_label;h_even_time[h_vertex]=even_time_token++;intfree_h=find_path_in_h(h_vertex);if(free_h==-1)continue;std::vector<int>path;intedge_id=h_parent_edge[free_h];assert(edge_id!=-1);path.push_back(edge_id);collect_path_in_h(path,next_h_vertex_through_edge(edge_id,free_h),h_vertex);paths.push_back(path);}assert(!paths.empty());for(constauto&path:paths)augment_path(path);for(auto&vertices:contracted_into)vertices.clear();}intsolve(){initialize_greedy_matching();while(phase_one())phase_two();returnmatching_size;}};public:GeneralMatching():GeneralMatching(0){}explicitGeneralMatching(intn):_n(n),_adj(n),_mate(n,-1),_mate_edge(n,-1),_calculated(false){assert(0<=n);}intsize()const{return_n;}intedge_count()const{returnint(_edges.size());}intadd_edge(intfrom,intto){assert(0<=from&&from<_n);assert(0<=to&&to<_n);assert(from!=to);intid=int(_edges.size());_edges.push_back(Edge{from,to,id,true});_adj[from].push_back(id);_adj[to].push_back(id);invalidate();returnid;}Edgeget_edge(inti)const{assert(0<=i&&i<int(_edges.size()));return_edges[i];}std::vector<Edge>edges(boolinclude_inactive=false)const{std::vector<Edge>result;result.reserve(_edges.size());for(constauto&e:_edges){if(include_inactive||e.alive)result.push_back(e);}returnresult;}voidset_edge_alive(intid,boolalive){assert(0<=id&&id<int(_edges.size()));_edges[id].alive=alive;invalidate();}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<int(_edges.size()));return_edges[id].alive;}intmax_matching(){MicaliVaziraniSolversolver(*this);intresult=solver.solve();_calculated=true;returnresult;}intmatching_size(){ensure_matching();intresult=0;for(intv=0;v<_n;v++){if(v<_mate[v])result++;}returnresult;}std::vector<int>mate(){ensure_matching();return_mate;}std::vector<int>mate_edge(){ensure_matching();return_mate_edge;}std::vector<Pair>matching(){ensure_matching();std::vector<Pair>result;for(intv=0;v<_n;v++){if(v<_mate[v])result.push_back(Pair{v,_mate[v],_mate_edge[v]});}returnresult;}std::optional<std::vector<int>>minimum_edge_cover(){ensure_matching();std::vector<int>result;std::vector<char>covered(_n,false),used_edge(_edges.size(),false);autouse_edge=[&](intid){if(used_edge[id])return;used_edge[id]=true;result.push_back(id);covered[_edges[id].from]=true;covered[_edges[id].to]=true;};for(intv=0;v<_n;v++){if(v<_mate[v])use_edge(_mate_edge[v]);}for(intv=0;v<_n;v++){if(covered[v])continue;intid=-1;for(intedge_id:_adj[v]){if(_edges[edge_id].alive){id=edge_id;break;}}if(id==-1)returnstd::nullopt;use_edge(id);}returnresult;}};structGeneralMatchingGraph{GeneralMatchingmatching;std::vector<int>original_edge_id;intoriginal_edge(intedge_id)const{assert(0<=edge_id&&edge_id<int(original_edge_id.size()));returnoriginal_edge_id[edge_id];}};template<classT>GeneralMatchingGraphmake_general_matching(constGraph<T>&g){GeneralMatchingGraphresult;result.matching=GeneralMatching(g.size());for(constauto&e:g.edges()){intid=result.matching.add_edge(e.from,e.to);if(int(result.original_edge_id.size())<=id)result.original_edge_id.resize(id+1);result.original_edge_id[id]=e.id;}returnresult;}}// namespace graph}// namespace m1une#line 10 "verify/graph/library_checker_general_matching.test.cpp"
intmain(){m1une::utilities::FastInputfast_input;m1une::utilities::FastOutputfast_output;intN,M;fast_input>>N>>M;m1une::graph::GeneralMatchinggm(N);while(M--){intu,v;fast_input>>u>>v;gm.add_edge(u,v);}fast_output<<gm.max_matching()<<'\n';for(autop:gm.matching()){fast_output<<p.from<<' '<<p.to<<'\n';}}