Test instructions: Every time the point adjacent to the first point is given, the Hamiltonian circuit is obtained after the direction graph is presented.
Reference: http://blog.csdn.net/volzkzg/article/details/7514103
Idea: From a point to the adjacent chain, forming a ring, and then the point is not on the ring added to the ring, the number of points on the ring is the Hamiltonian loop;
#include <cstdio>#include<cstdlib>#include<cstring>#include<string>#include<iostream>using namespacestd; Const intMN =1100; intN,k,i,j,listnum; intL[mn],r[mn],head,tail; BOOLADJ[MN][MN] ={0}; BOOLVISIT[MN]; strings; voidReverse () {//checked intTmp[mn],t = head,num=1; Tmp[num]=Head; while(t!=tail) {T=r[t];tmp[++num]=T; }tmp[++num]=tail; if(Adj[head][tail]) {R[tail]= head; L[head] =tail; return ; } Else for(intI=2; i<num-1;++i)if(adj[head][tmp[i+1]] &&Adj[tail][tmp[i]]) {L[head]= R[head]; R[head] = tmp[i+1]; L[tmp[i+1]] = head; R[tail] =Tmp[i]; R[tmp[i]]=l[tmp[i]]; L[tmp[i]] =tail; for(intj = I1; j>=2;--j) { intp =l[tmp[J]; l[tmp[J]]= r[tmp[J]; r[tmp[J]]=p; } return; } } voidAdd () {intTmp[mn],t = head,num=1; Tmp[num]=Head; while(t!=tail) {T=r[t];tmp[++num]=T; }tmp[++num]=tail;intPOS; for(intI=1; i<=n;++i)if(Visit[i]) {pos = i;visit[i]=false; Break;} for(inti =1; i<=num;++i)if(Adj[tmp[i]][pos]) {head= R[tmp[i]];tail =POS; R[tmp[i]]=POS; L[pos]=Tmp[i]; R[pos]=0; ListNum++; return; } } intFindhead () {//checked for(intI=1; i<=n;++i)if(Visit[i] &&Adj[head][i]) {L[head]= i; R[i]=head; l[i]=0; visit[i]=false; returni; } return 0; } intFindtail () {//checked for(intI=1; i<=n;++i)if(Visit[i] &&Adj[tail][i]) {R[tail]= i; L[i]=tail; r[i]=0; visit[i]=false; returni; } return 0; } voidprint () {intTmp[mn],t =1, num=1; Tmp[num]=1; while(r[t]!=1) {T=r[t];tmp[++num]=T; } for(intI=1; i<=num;++i) cout << Tmp[i] <<" " ; cout<<1<<" "<<Endl; } voidInsert () {intV//checked//continuous expansion of the left and right ends while(V=findhead ()) {head = V;listnum + +;} while(V=findtail ()) {tail = V;listnum + +;} Reverse ();//Let Hamilton Road becomes Hamiltonian circuit if(ListNum = = N) print ();//if the element in the loop satisfies N, then the output Else{ intTMP =ListNum; Add (); Insert (); } } voidInit () {//checkedCIN >>N;getchar (); for(i =1; I <= n;++i) {getline (cin,s); K=0; for(intj=0; J<s.size (); + +j)if(s[j]!=' ') k=k*Ten+s[j]-'0'; Else{adj[i][k]=true; k=0;} if(k!=0) {Adj[i][k]=true; k=0; }}memset (Visit,true,sizeof(visit)); Tail= Head = ListNum =1; visit[1]=false; } intMain () {init (); Insert (); return 0; }
SGU 122 The book (Hamilton Circuit)