#include #include #include using namespace atcoder; using mint = modint1000000007; using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf 1000000000 vector A,B; void go(vector ind,vector a,vector b){ int n = ind.size(); sort(ind.begin(),ind.end()); scc_graph S(n); rep(i,a.size()){ int x = distance(ind.begin(),lower_bound(ind.begin(),ind.end(),a[i])); int y = distance(ind.begin(),lower_bound(ind.begin(),ind.end(),b[i])); S.add_edge(x,y); } vector> s = S.scc(); rep(i,s.size()){ if(i+1!=s.size()){ A.push_back(ind[s[i][0]]); B.push_back(ind[s[i+1][0]]); } if(s[i].size()>=2){ rep(j,s[i].size()){ int x = s[i][j]; int y = s[i][(j+1)%s[i].size()]; A.push_back(ind[x]); B.push_back(ind[y]); } } } } int main(){ int N,M; cin>>N>>M; vector a(M),b(M); dsu D(N); rep(i,M){ scanf("%d %d",&a[i],&b[i]); a[i]--;b[i]--; D.merge(a[i],b[i]); } vector pos(N); vector> ret = D.groups(); rep(i,ret.size()){ rep(j,ret[i].size()){ pos[ret[i][j]] = i; } } // cout<<'a'<> aa(ret.size()),bb(ret.size()); rep(i,M){ int ind = pos[a[i]]; aa[ind].push_back(a[i]); bb[ind].push_back(b[i]); } rep(i,ret.size()){ go(ret[i],aa[i],bb[i]); } //cout<<'a'<