According to the Hamilton loop algorithm described above in usaco, we do not fully understand it... The general idea is that the method will process other nodes first, and then add the node to the path. So what we get is the reverse order of a path. If you want to obtain the correct sequence (Lexicographic Order, from small to large), you still need to follow the sequence you want (that is, starting from the small odd point, then, the smallest of the adjacent nodes is processed at each processing time, and the output is in reverse order.
The Code is as follows:
/*ID: thestor1LANG: C++TASK: fence*/#include <iostream>#include <cmath>#include <cstdio>#include <cstring>#include <vector>#include <cassert>#include <string>#include <algorithm>#include <stack>#include <set>#include <queue>using namespace std;const int maxnum = 500;int main(){FILE *fin = fopen ("fence.in", "r");FILE *fout = fopen ("fence.out", "w");//freopen("log_1.txt", "w", stdout);int f;fscanf(fin, "%d", &f);vector<multiset<int> > vertexes;vertexes.resize(maxnum);fill(vertexes.begin(), vertexes.end(), multiset<int>());int maxv = -1;for(int i = 0; i < f; ++i){int u, v;fscanf(fin, "%d%d", &u, &v);u--, v--;vertexes[u].insert(v);vertexes[v].insert(u);maxv = max(u, v) > maxv ? max(u, v) : maxv;}int u = -1;//for(int i = maxv; i >= 0; --i)for(int i = 0; i <= maxv; ++i){if(vertexes[i].size() % 2 == 1){u = i;break;}}if(u == -1){u = 0;}stack<int> st;st.push(u);stack<int> path;while(!st.empty()){int u = st.top();//st.pop();if(vertexes[u].empty()){//fprintf(fout, "%d\n", u + 1);path.push(u + 1);st.pop();}else{int v = *vertexes[u].begin();vertexes[u].erase(vertexes[u].begin());vertexes[v].erase(vertexes[v].find(u));st.push(v);}}while(!path.empty()){fprintf(fout, "%d\n", path.top());path.pop();}return 0;}