Usaco riding the fences solution report

Source: Internet
Author: User

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;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.