Test instructions: A graph of N-point n points is given to determine if there is a Hamiltonian path.
Idea: First use and check the set to determine whether the diagram is connected, and then from the smallest point of the degree of backtracking, to see if a Hamiltonian path can be found.
1#include <iostream>2#include <cstring>3#include <cstdio>4#include <Set>5 using namespacestd;6 7 Const intINF =999999;8 Const intN =1001;9 intF[n];Ten intD[n]; One intHead[n]; A BOOLVisit[n]; - intN, E; - the voidInit () - { -E =0; -memset (D,0,sizeof(d)); +Memset (Head,-1,sizeof(head)); -memset (Visit,0,sizeof(visit)); + for(inti =1; i < N; i++) F[i] =i; A } at - structEdge - { - intV, next; -} edge[n <<1]; - in voidAddedge (intUintv) - { toEDGE[E].V =v; +Edge[e].next =Head[u]; -Head[u] = e++; the } * $ intFINDF (intx)Panax Notoginseng { - if(f[x]! = x) F[x] =findf (f[x]); the returnF[x]; + } A the BOOLUnion_set (intXinty) + { -x = FINDF (x), y =findf (y); $ if(x = =y) $ { - return false; - } the Else - {WuyiF[X] =y; the return true; - } Wu } - About BOOLDfsintUintCNT) $ { - if(cnt = = N)return true; - for(inti = Head[u]; I! =-1; i =edge[i].next) - { A intv =edge[i].v; + if( !Visit[v]) the { -VISIT[V] =1; $ if(Dfs (V, CNT +1) )return true; theVISIT[V] =0; the } the } the return false; - } in the intMain () the { About while(SCANF ("%d", &n)! =EOF) the { the init (); the intc =0; + for(inti =1; I <= N; i++ ) - { the intu, v;Bayiscanf"%d%d", &u, &v); the Addedge (U, v); the Addedge (V, u); -d[u]++, d[v]++; - if(Union_set (U, v)) C + +; the } the if(c! = N-1 ) the { thePuts"NO"); - Continue; the } thed[0] =INF; the intK =0;94 for(inti =1; I <= N; i++ ) the { the if(D[i] <D[k]) the {98K =i; About } - } 101VISIT[K] =1;102 if(Dfs (k,1 ) )103 {104Puts"YES"); the }106 Else107 {108Puts"NO");109 } the }111 return 0; the}
HDU 5424 backtracking + and check-set to determine connectivity